How to remove foreign key constraint by using migration in laravel ?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post i will show you How to remove foreign key constraint by using migration in laravel ?Sometimes we need to remove a database column that hosts a foreign key with relationship, and we need to add wrong column with foreign key constraint on the table. So at that time we must have to remove that column from the table. Now here, we will be remove from the foreign key constraint by using the migration in laravel 6, laravel 7 or laravel 8 any version of laravel project.

Sometimes we can’t remove this directly by using dropColumn() because we did apply this as foreign key constraint so we should drop the foreign key constraint of that column by using dropForeign() and then we can delete the column by using dropColumn(). So we can see this in the bellow migration file, at first i will add aat migration with wrong column then other migration write 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');
});

Read Also : How to Create Custom Blade Directive in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →