How To Use Enums With Laravel 9?

Enver Şanlı
4 min readFeb 11, 2022
Laravel Enum Feature

Hello Laravel lovers,

I can hear your heart’s sound! I know you are so excited about the new Laravel version. The version was released previous days and there are many differences and new features. We will discuss ENUMS with Laravel 9. I always use that in my projects, it really makes it to use easier and more readable. You can use it too in your projects, I’m sure you will like it.

Why We Use Enums?

Consider that, you are developing an advanced project and you have user roles and roles that exist keys like “admin”, “editor”, “visitor”, etc but you will use it many times in your project. So, it will be a problem for your project’s quality. The project will not be readable, extendable, etc. These expressions are so important for development.

Let’s see an example with a bad method for quality.

You have a User table and you want to create a new user as an editor. Your table exists a role column for this.

User::create(['role'      => 'editor',
'full_name' => 'Aziz Sancar',
'tag' => 'Nobel Prize',
'subject' => 'Chemistry'
]);

As you can see in our example, we directly wrote the “editor” word for our role. Maybe our example is not enough to explain this problem but consider that, you used the user roles so many times in your project and you wanted to change something. What will happen then? Yes, it’s time to make it easier with enums.

Let’s create our user role enum class (I use PhpStorm, you can create it with your IDE):

Laravel 9 Enum Class

After creating that class, you need to change the class definition to enum but you need to install PHP 8.1 because enum works only with PHP 8.1. If you want to use it as a class, you can use enums with older PHP versions, it’s only for enum definition instead of class.

Php 8.1 Enum

I chanced class definition to enum and I got this error with an underline because my PHP version was 8.0 then I chanced my PHP version (I use valet and you can read this article learn about that) and clicked the “Switch to PHP8.1 language level” option to fix it. Now, we can describe our role keys.

Laravel 9 Enum Error

Wait! Still, we have errors after definition. We need to cast the response as a string to fix it.

Laravel Enum Cast

As you can see, we don’t have any problem right now. I want to add a function to get all role parameters to use with migration.

<?php
namespace App\Enum;


enum UserRoleEnum:string
{
case ADMIN = 'admin';
case VISITOR = 'visitor';
case EDITOR = 'editor';
}

As you can see, we returned all role types as strings.

Next, we created our migration to describe user table columns.

Schema::create('users', function (Blueprint $table) {
$table->id();
/** ENUM */
$table->string('role');
/** end ENUM */
$table->string('full_name');
$table->string('tag')->nullable();
$table->string('subject')->nullable();
$table->timestamps();
});

Role column will exist all role types but we didn’t use <enum> column type because it affects also the readable code rule. So, we will cast it with our model.

protected $casts = [
'email_verified_at' => 'datetime',
'role' => UserRoleEnum::class
];

Let’s create our first record!

Route::get('/', function () {
\App\Models\User::create([
'role' => \App\Enum\UserRoleEnum::EDITOR,
'full_name' => 'Aziz Sancar',
]);
});
DB Record

As you can see our record was created successfully. Now, I will fill our table with a few fake data to use in queries with different user roles.

Let’s request only for editors.

Route::get('/get-editors', function () {
$editors = \App\Models\User::where('role', \App\Enum\UserRoleEnum::EDITOR)->get();

dd($editors);
});
Query Response

As you can see above, responded to only 5 rows with our editor role query. That’s worked as expected but we really used an advanced way to do that! Any developer can read easily with this way in advanced projects.

By the way, would you like to gel all user roles ? It’s easy too!

Route::get('/get-all-enums', function (){
dd(\App\Enum\UserRoleEnum::cases());
});

Thank you for your time and I hope you liked the content!

See you at the next feature!

Enver ŞANLI

Laravel Developer, Social Thinker & Farmer

--

--