Remove a foreign key constraint in a Laravel migration
August 1, 2022 ‐ 1 min read
Dropping a foreign key constraint might sound like an odd thing to do. But in some cases you need to. For example, when you turn a foreign key field into a polymorphic relationship.
In such a case you want to use the dropForeign()
method, which takes the name of the foreign key constraint in your database. This name takes the following form: {table}_{column}_foreign
.
Thus, if you would have a foreign key constraint in the tasks
table for the user_id
column, you could drop the key constraint using the following migration.
<?php
public function up()
{
Schema::table('tasks', function (Blueprint $table) {
$table->dropForeign('tasks_user_id_foreign');
});
}