How To Drop Foreign Key In Laravel 10 Migration

Websolutionstuff
2 min readJul 3, 2023

--

In this article, we will see how to drop the foreign key in laravel 10 migration. Here, we will learn about laravel 10 drop foreign key using migration.

To drop a foreign key, you may use the dropForeign method, passing the name of the foreign key constraint to be deleted as an argument.

Foreign key constraints use the same naming convention as indexes. you can't remove directly using dropColumn() because we did apply a foreign key constraint so we should drop the foreign key constraint of that column using dropForeign() and then we can delete the column using dropColumn().

So, let's see how to drop the foreign key in laravel 10 migration, laravel 10 drop foreign key using migration, drop foreign key laravel migration 10, remove foreign key laravel 10 migration, laravel 10 migration drop foreign key.

In other words, the foreign key constraint name is based on the name of the table and the columns in the constraint, followed by a "_foreign" suffix.

$table->dropForeign('posts_user_id_foreign');

Alternatively, you may pass an array containing the column name that holds the foreign key to the dropForeign method. The array will be converted to a foreign key constraint name using Laravel's constraint naming conventions.

$table->dropForeign(['user_id']);

Example:

Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('profile_picture');
$table->string('password', 60);
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->timestamps();
});

Drop Column Migration:

Schema::table('users', function (Blueprint $table) {
$table->dropForeign('users_post_id_foreign');
$table->dropColumn('post_id');
});

--

--

Websolutionstuff
Websolutionstuff

Written by Websolutionstuff

I am Laravel and PHP Developer. I have also Good Knowledge of JavaScript, jQuery, Bootstrap and REST API. Visit Website: http://websolutionstuff.com/

No responses yet