• Reading time ~ 1 min
  • 07.03.2023

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!

  1. Episode 1: Laravel 9: Stub Migrations
  2. Episode 2: Laravel 9: New Designs
  3. Episode 3: Laravel 9: New Helpers
  4. Episode 4: Laravel 9: Enums!
  5. 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:

laravel 9 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.

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 9 enums

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!

laravel 9 enums migrations

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:

laravel 9 enums casting

And we can access the attribute directly:

laravel 9 enums accessors

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

laravel 9 enums methods

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297