Nikita Yunoshev
Nikita Yunoshev

Reputation: 409

A bug with renaming existing column in Laravel migrations

I added a new migration to rename an old column. Everything seems correct in this code, for me:

public function up()
{
   Schema::table('reports', function (Blueprint $table) {
        $table->renameColumn('reporter_id', 'created_by');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('reports', function (Blueprint $table) {
        $table->renameColumn('created_by', 'reporter_id');
    });
}

But then I faced an error:

In Connection.php line 664: SQLSTATE[0A000]: Feature not supported: 1846 ALGORITHM=COPY is not supported. Reason: Columns participating in a foreign key are renamed. Try ALGORITHM=INPLACE. (SQL: ALTER TABLE reports CHANGE reporter_id created_b    y INT NOT NULL)                                                                                                                                                                                                          
In PDOStatement.php line 140: SQLSTATE[0A000]: Feature not supported: 1846 ALGORITHM=COPY is not supported. Reason: Columns participating in a foreign key are renamed. Try ALGORITHM=INPLACE.
In PDOStatement.php line 138: SQLSTATE[0A000]: Feature not supported: 1846 ALGORITHM=COPY is not supported. Reason: Columns participating in a foreign key are renamed. Try ALGORITHM=INPLACE. `

Could you help me to fix this?

Upvotes: 4

Views: 1269

Answers (2)

Stuart Steedman
Stuart Steedman

Reputation: 146

I've encountered this too - it makes no sense, because when I use my standard SQL client to rename the same field ... it works. But it just doesn't work as a migration script. Thus, I ended up running the RENAME inside a DB::statement and that worked for me:

     /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {

        DB::statement("ALTER TABLE `mydb`.`mytable`   
          CHANGE `currentfieldname` `newfieldname` 
          INT(10) UNSIGNED NOT NULL;");

    }

Upvotes: 1

Sohel0415
Sohel0415

Reputation: 9853

First drop koreign key on up method.

public function up()
{
  Schema::table('reports', function (Blueprint $table) {
     $table->dropForeign('reports_reporter_id_foreign');
     $table->renameColumn('reporter_id', 'created_by');
  });
}

Then add foreign key again on down method.

public function down()
{
    Schema::table('reports', function (Blueprint $table) {
        $table->renameColumn('created_by', 'reporter_id');
        $table->foreign('reporter_id')->references('id')->on('your_related_table')->onDelete('cascade');
    });
}

Upvotes: 1

Related Questions