Laravel - How to remove foreign key constraint using migration?
Sometimes it can be agreeable to remove a database column that hosts a foreign key relationship, and we add wrong column with foreign key constraint on table, At that time we must remove that column from table. here, we will remove foreign key constraint using migration in laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10.
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(). You can see as bellw migration, first i added migration with wrong column then other migration for remove that column.
Wrong Column Migration:
Schema::create('admins', function (Blueprint $table) {
$table->increments('id');
$table->string('fullname');
$table->string('email')->unique();
$table->string('imagepath');
$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('admins', function (Blueprint $table) {
$table->dropForeign('admins_post_id_foreign');
$table->dropColumn('post_id');
});

Hardik Savani
I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.