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!
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.
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!
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!
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:
According to Laravel docs, Almost all known methods we use on collections are also available on enums likes:
That’s it… Any question?