Laravel drop foreign Key in Migration
21,346
Solution 1
You just need to disable foreign key checks before you drop the table then enable them again after like this:
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
Schema::dropIfExists('devices');
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
Solution 2
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']);
Solution 3
Try this ways...
public function down()
{
Schema::dropIfExists('devices');
}
//Or this
public function down(){
Schema::table('devices', function (Blueprint $table) {
$table->dropForeign(['client_id']);
$table->dropColumn('client_id');
$table->drop('devices');
});
}
Author by
Jon not doe xx
Updated on August 16, 2020Comments
-
Jon not doe xx almost 4 years
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 keydevices_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
-
Jon not doe xx almost 6 yearsHi there is a foreign key Client_id so I cant drop it that easily
-
Jon not doe xx almost 6 yearsThere is a foreign key I can't drop it that easily
-
Jon not doe xx almost 6 years
Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table
devices)
-
Jonas Staudenmeir almost 6 yearsAre there foreign keys in other tables that reference the
devices
table? -
Sizzling Code over 4 yearswhy drop the whole table in down method when we are not creating table in up method?
-
shamaseen almost 4 yearsYou can't drop the whole table while it has a foreign key.
-
Daniel Hernández almost 3 yearsThis works when you didn't give it a different FKs name that Laravel sets by default.