Soon, Laravel 9 wil release and there are some new features that we can use them.
This series is going to be a sequel about Laravel framework version 9 and in each article we will review a new feature!
And yes! Finally we have official support for Enums in php 8.1 although we could add them to Laravel framework by using third-party packages like spatie/enums.
But what are enums in php?
They are just singleton objects and the syntax to define them is as below:
Gladly, we can do so much thing with Laravel Enums and in this article we are going to cover some of the most important usages.
1. Route Bindings With Enums
Laravel 9.x has ability to type hint on our route… think it as a route-model binding but instead of model we have enums! Let see an example:
and in web.php:
With these codes, Laravel automatically will recognize category type and if we don’t pass any of predefined types, it will return an HTTP 404 response!
2. Enums And Migrations
We can use enum()
method as following example to create a column with enum type, just be careful by choosing a proper name because renaming an enum column is not currently supported!
3. Enum Attribute Casting
Now our dearest, Eloquent ORM will let us to cast attributes to PHP enums. We just need to use $casts
property array on desired model:
And we can access the attribute directly:
4. Enum Methods
According to Laravel docs, Almost all known methods we use on collections are also available on enums likes:
That’s it… Any question?
Top comments (0)