Laravel - How to remove foreign key constraint using migration?

By Hardik Savani | July 1, 2016 | | 1186 Viewer | Category : Laravel


Share this post:

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.

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');

});