DEV Community

Cover image for Laravel 9: Enums!
Reza Khademi
Reza Khademi

Posted on

Laravel 9: Enums!

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:

php enums

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:

laravel enums

and in web.php:

laravel enums route bindings

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!

laravel enum migrations

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:

laravel enums casting

And we can access the attribute directly:

laravel accessing enums

4. Enum Methods

According to Laravel docs, Almost all known methods we use on collections are also available on enums likes:

laravel enum methods

That’s it… Any question?

Discussion (0)