3

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;
}
gfaster
  • 157
  • 2
  • 12

2 Answers2

4

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()));
xuma
  • 466
  • 3
  • 5
  • 1
    Won't this break your codebase if when this is deployed you change the internal values of the enum? The migration won't run again every time.. – Niels Bosman Aug 17 '22 at 06:59
0
enum DayOfWeek {
    case Monday;
    case Tuesday;
    case Wednesday;
    case Thursday;
    case Friday;
    case Saturday;
    case Sunday;
}


$table->enum('day_of_week', array_column(DayOfWeek::cases(), 'name'));