Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change enum type column in laravel migration?

I am using Laravel 5.1 and I have a table called packages with this structure:

id              int(11) weight          decimal(10,2)            weight_unit     enum('Kg.', 'Gm.') 

I would like to change the weight_unit enum to:

weight_unit enum('Grams','Kgs.','Pounds')

For this I create the following migration:

public function up() {     Schema::table('packages', function ($table) {         $table->enum('weight_unit', array('Grams','Kgs.','Pounds'))->nullable()->change();     }); } 

But when I run the migration I receive an error:

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

How can I change this enum?

like image 901
Vinod VT Avatar asked Nov 03 '15 10:11

Vinod VT


People also ask

How can I rename column in laravel using migration?

To rename a column, you may use the renameColumn method on the Schema builder. Before renaming a column, be sure to add the doctrine/dbal dependency to your composer. json file: Schema::table('users', function (Blueprint $table) { $table->renameColumn('from', 'to'); });

What is enum in laravel?

Laravel Enum is a package by Ben Sampson that adds support for creating enums in PHP and includes a generator for Laravel. Here's an example of what an Enum class looks like using this package: 3namespace App\Enums; 5use BenSampo\Enum\Enum; 7final class UserType extends Enum.

How do I change the default value in laravel migration?

In our case we are going to do second option - create new migration. If we roll back this migration, we need to remove default value from that field using migration and this is how to do it: Schema::table('photos', function (Blueprint $table) { $table->integer('order')->default(NULL)->change(); });


2 Answers

Use the DB::statement method:

DB::statement("ALTER TABLE packages MODIFY COLUMN weight_unit ENUM('Grams', 'Kgs', 'Pounds')"); 
like image 103
Tayyab Hussain Avatar answered Sep 27 '22 21:09

Tayyab Hussain


This worked for me when adding a new enum value to the modified enum column.

Add the following to the up() method:

DB::statement("ALTER TABLE packages MODIFY weight_unit ENUM('Grams', 'Kgs', 'Pounds', 'new value') NOT NULL"); 

Then in the down() method you can revert the change that was made:

DB::statement("ALTER TABLE packages MODIFY weight_unit ENUM('Grams', 'Kgs', 'Pounds') NOT NULL"); 

Note: before the enum value is removed it needs to be changed to another enum value that will be retained.

like image 32
Ray Hunter Avatar answered Sep 27 '22 21:09

Ray Hunter