4

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;
}

2 Answers 2

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()));
Sign up to request clarification or add additional context in comments.

1 Comment

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..
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'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.