Search code examples
laravellaravel-4migration

Drop and then create same columns in current up migration function


Schema::table('users', function (Blueprint $table) {
            $table->dropTimestamps();
            $table->dropColumn(['email', 'bio']);

            $table->string('email', 20)->unique()->after('id');
            $table->string('bio', 150)->after('surname');
            $table->timestamps();
        });

That is what I've got now. So, I have the columns existing atm in my table, but I want to modify and re-arrange them a bit. But when I run the migration, I get SQL error that email column exists. And I will probably get the same error for the bio and timestamps as well. I kind of understand why this happens, so what am I asking is just for a workaround.

Is it possible to make what I want inside one single migration, or I have to create a migration for deleting the columns and then a separate migration for creating them the way I want?


Solution

  • Just break the schema up into two calls

    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropTimestamps();
            $table->dropColumn(['email', 'bio']);
        });
    
        Schema::table('users', function (Blueprint $table) {
            $table->string('email', 20)->unique()->after('id');
            $table->string('bio', 150)->after('surname');
            $table->timestamps();
        });
    }
    

    This way the change is occurring in one migration with two database calls.