Laravel 9 is here 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!
- Episode 1: Laravel 9: Stub Migrations
- Episode 2: Laravel 9: New Designs
- Episode 3: Laravel 9: New Helpers
- Episode 4: Laravel 9: Enums!
- Episode 5: Laravel 9: Full Text Index & SwiftMailer
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.
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 in 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: