Home > Back-end >  Laravel migration: using a native PHP enum
Laravel migration: using a native PHP enum

Time:05-07

In PHP 8.1, native support for enums were introduced. How can I use them in a Laravel Migration?

My first thought would be something like this, but it does not work.

// migration
public function up()
    {
        Schema::create('school_days', function (Blueprint $table) {
            $table->id();
            $table->enum('day_of_week', \App\Enums\DayOfWeek::cases());
        });
    }
// DayOfWeek.php
enum DayOfWeek {
    case: Monday;
    case: Tuesday;
    case: Wednesday;
    case: Thursday;
    case: Friday;
    case: Saturday;
    case: Sunday;
}

CodePudding user response:

I'm not sure that $table->enum implemented enums yet but you can like this;

enum DayOfWeek {
    case Monday;
    case Tuesday;
    case Wednesday;
    case Thursday;
    case Friday;
    case Saturday;
    case Sunday;
}


$table->enum('day_of_week', array_map(fn($day) => $day->name, DayOfWeek::cases()));
  • Related