Learn How to Use Laravel Enum Casting

Laravel 9 has introduced enum model attribute casting, which makes it easier than ever to use enums in your application. With the help of an enum class and model casting, you can easily set up your table with specific enum values.

If you’re looking to use the enum data type in Laravel, you can do so easily with the help of enum model attribute casting. In this post, we’ll walk you through a step-by-step example to show you how to use enums in Laravel and cast them to a model attribute.

First, you’ll need to create a migration with a string column called "status" and a default value of "pending". Then, you can create a model and set the cast to your enum class. With this approach, you won’t have to create a new migration every time you want to add a new enum value to your table.

Laravel 9 has introduced enum model attribute casting, which makes it easier than ever to use enums in your application. With the help of an enum class and model casting, you can easily set up your table with specific enum values.

In this example, we’ll guide you through the process of creating a migration with a string column, creating a model with a cast to your enum class, and creating an enum class with specific values. Follow along with our step-by-step example to learn how to use Laravel enum attribute casting today.

Step 1: Install Laravel

If you haven’t already created a Laravel app, run the following command to install Laravel:

composer create-project laravel/laravel example-app

It will install new laravel app inside example-app folder. For further commands, go inside the example-app folder. There are many other ways to install the laravel application. Click on this link to visit Laravel installation documentation.

Step 2: Create Laravel Migration

Create a migration for the "enquiries" table with name, email, phone and status columns, as well as a model for the enquiries table. run the following command to create migration:

php artisan make:migration create_enquiries_table

Update the migration file with the following code:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        Schema::create('enquiries', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email');
            $table->bigInteger('phone');
            $table->string('status')->default('pending');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('enquiries');
    }
};

Now, we are ready with our migration script. Run the following command to create the "enquiries" table:

php artisan migrate

Note that, we created the table with "status" value as "pending" by default.

Step 3: Create Enum Class

Create the Enums folder and EnquiryStatusEnum.php class inside the Enums to define all enum values as follows:

namespace App\Enums;

enum EnquiryStatusEnum: string {
    case Pending = 'pending';
    case InProgress = 'in-progress';
    case Closed = 'closed';
}

Step 4: Create Model

Now, we need a model file for our enquiries table. To create a model, run the following command:

php artisan make:model Enquiry

It will create Enquiry.php file inside the app/Models folder. Change the model file as follows:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Enums\EnquiryStatusEnum;

class Enquiry extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'email', 'phone', 'status'
    ];

    protected $casts = [
        'status' => EnquiryStatusEnum::class
    ];
}

Here, we defined a $casts variable, which will cast the status variable with EnquiryStatusEnum class.

Step 5: Create Controller

Now, create a controller file using the following command:

php artisan make:controller EnquiryController

It will create the EnquiryController.php file inside the app/Http/Controllers folder. Write the following code inside index() method to create item records with an array and access as an array:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Enquiry;
use App\Enums\EnquiryStatusEnum;

class EnquiryController extends Controller
{
    public function index()
    {
        $input = [
            'name' => 'Test User',
            'email' => 'test@example.org',
            'phone' => 6358465465
            'status' => EnquiryStatusEnum::Active
        ];

        $enquiry = Enquiry::create($input);

        dd($enquiry->status, $enquiry->status->value);
    }
}

In above code, we have added a new entry inside the enquiries table and right after that we displayed the enquiry status.

Step 6: Create Route

To create a route for testing our code, add the following lines to routes/web.php file:

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\EnquiryController;

Route::get('enquiry', [EnquiryController::class, 'index']);

Step 7: Run the Laravel app

To run the laravel app, use the following command:

php artisan serve

Open your web browser and enter the following URL to view the app output:

http://localhost:8000/enquiry

You can see the database output and print variable output:

App\Enums\EnquiryStatusEnum {#1781
    name: "InProgress"
    value: "in-progress"
}

in-progress

You can see the database output, which is showing casted values from EnquiryStatusEnum. And second parameter is value output, which is showing it’s corresponding string value "in-progress".

With these simple steps, you can easily use enum in Laravel without the need for constant migrations.