Laravel 8 Migration - change enum values

Viewed 5339

I'm trying to change an enum value in database with Laravel migrations.

In first, i have tried this classic change :

Schema::table('questionnaires', function ($table) {
    $table->enum('type', ['image', 'sound', 'video'])->nullable()->default('image')->change();
});

But I got the following error :

Unknown database type enum requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it

I solved my problem by doing SQL directly :

DB::statement("ALTER TABLE questionnaires MODIFY COLUMN type ENUM('image', 'sound', 'video') DEFAULT 'image'");

But it does not seem optimal to me...

Is there a solution more in "agreement" with Laravel 8, without going through pure SQL?

Thanks

1 Answers

Explanation

To elaborate a little bit more on this subject.

As noted here ENUMs cannot be reverse engineered into a certain type. Each ENUM is a value of it's own. Hence, you must specifically say to Laravel which type the ENUMs are.

This seems to be an issue with all versions of Laravel

In documentation for each version, i.e. https://laravel.com/docs/8.x/migrations#renaming-columns, you can find that changing enum fields is not supported. As noted here the DB statement inside your migration is the best workaround for now.

DB::statement("ALTER TABLE questionnaires MODIFY COLUMN type ENUM('image', 'sound', 'video') DEFAULT 'image'");

Migration files fix

This option is the above commented GitHub link which advises you to put this line of code before the actual migration inside up() method of migration file.

DB::connection()->getDoctrineSchemaManager()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');

Models/enum types fix

I think this one is a lot less straightforward then the above mentioned, but still exists as a valid option, so I will put it here,

You can read an official doctrine-project website page here which shows you how to this thing from within models / enum types.

Related