skip to Main Content

I am trying to change a varchar column to an enum type. I wrote and ran my migration – create new column, logic to set the values, drop old column, rename new column. At first thought it all went well, but on closer inspection, the column was still a varchar not an enum, but the values had been (correctly) changed.

I rolled back, and then just ran the first 2 steps, adding the enum column and setting the values, but not dropping/renaming and the new column was correctly added as an enum.

Why is this not working as expected?

Here’s my up:

    public function up()
    {
        Schema::table('lifts', function (Blueprint $table) {

            $table->enum('lift_type', ['magic_carpet', 'rope_tow', 'platter', 't_bar','j_bar', 'fixed_chair', 'express_chair', 'bubble_chair', 'gondola', 'chondola', 'tram', 'unknown'])->default('unknown')->after('type');
        });

        $lifts = Lift::all();
        $lifts->each(function ($lift) {
            switch ($lift->type) {
                case "Bubble Chair":
                    $lift->lift_type = "bubble_chair";
                    break;
              ...
                default:
                    $lift->lift_type = "unknown";
                    break;
                }
            $lift->save();
        });

        Schema::table('lifts', function (Blueprint $table) {

            $table->dropColumn('type');
        });

        //Rename the column

        Schema::table('lifts', function (Blueprint $table) {
            $table->renameColumn('lift_type', 'type');
        });
    }

2

Answers


  1. Chosen as BEST ANSWER

    For anyone else who comes across this, it turns out you can't rename an enum column (it is in the docs, but I missed it the first time!)

    The solution was to rename first (to type_old), then add the enum with the correct name (then assign correct values, then delete the renamed column)


  2. You should include change method while defining enum type.

    Example

         Schema::table('lifts', function (Blueprint $table) {
    
            $table->enum('lift_type', ['magic_carpet', 'rope_tow', 'platter', 
            't_bar','j_bar', 'fixed_chair', 'express_chair', 'bubble_chair', 
            'gondola', 'chondola', 'tram', 'unknown'])
            ->default('unknown')
            ->after('type')
            ->change() //add this;
         });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search