Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel drop foreign Key in Migration

I want to create a Migration which shall drop a table. I created the Migration like this:

Schema::table('devices', function (Blueprint $table) {
    $table->increments('id');
    $table->unsignedInteger('client_id')->nullable();
    $table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
});

And now I try to drop it like this:

    Schema::table('devices', function (Blueprint $table) {
        $table->dropForeign('devices_client_id_foreign');
        $table->drop('devices');
    });

But I get following error:

In Connection.php line 664:

  SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'devices_client_id_foreign'; check that column/key exists (SQL:

alter table devices drop foreign key devices_client_id_foreign)

In PDOStatement.php line 144:

  SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'devices_client_id_foreign'; check that column/key exists


In PDOStatement.php line 142:

  SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'devices_client_id_foreign'; check that column/key exists
like image 302
Jon not doe xx Avatar asked Aug 15 '18 14:08

Jon not doe xx


People also ask

How do I drop a foreign key in migration?

You can use this: Schema::table('despatch_discrepancies', function (Blueprint $table) { $table->dropForeign(['pick_detail_id']); $table->dropColumn('pick_detail_id'); }); If you take a peak at dropForeign source, it will build the foreign key index name for you if you pass the column name as an array.

How do you remove a foreign key constraint in migration?

But we can't remove directly using dropColumn() because we did apply foreign key constraint so we should drop foreign key constraint of that column using dropForeign() and then we can delete column using dropColumn().


1 Answers

You can use this answer. https://stackoverflow.com/a/30177480/8513937

Pass to dropForeign the column name as array. Internally, Laravel drops the associated foreign key.

$table->dropForeign(['client_id']);
like image 86
gandarrillas Avatar answered Oct 05 '22 23:10

gandarrillas