How to Drop Foreign Key Constraint in Laravel Migration?

By Hardik Savani April 16, 2024 Category : Laravel

Hi Artisan,

This post will give you an example of laravel migration remove foreign key. This post will give you a simple example of laravel migration drop foreign key. If you have a question about remove foreign key constraint laravel then I will give a simple example with a solution. I’m going to show you about laravel migration remove foreign key constraint.

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, laravel 10 and laravel 11.

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.

Example: Laravel Add Foreign Key using Migration

Create Migration Command:

php artisan make:migration create_posts_table

database/migrations/2021_04_01_040458_create_posts_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('posts', function (Blueprint $table) {

$table->id();

$table->string('name');

$table->text('body');

$table->timestamps();

});

Schema::create('comments', function (Blueprint $table) {

$table->id();

$table->unsignedBigInteger('user_id');

$table->unsignedBigInteger('post_id');

$table->text('comment');

$table->timestamps();

$table->foreign('user_id')->references('id')->on('users');

$table->foreign('post_id')->references('id')->on('posts');

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('comments');

Schema::dropIfExists('posts');

}

}

run migration

php artisan migrate

Output:

Example: Laravel Drop Foreign Key using Migration

Create Migration Command:

php artisan make:migration drop_posts_table

database/migrations/2021_04_01_040458_drop_posts_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('comments', function (Blueprint $table) {

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

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

}

}

run migration

php artisan migrate

I hope it can help you...

Tags :
Shares