How to add Delete cascade to existing column in Laravel?

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

Today now in this tutorial i will show you how to add delete cascade to existing column in laravel. So whenever we are making table by using migration with foreign key. As like i will give you a example as under and we forgot to set delete cascade on table and then we know how can we add delete cascade in existing table. so let’s start and see our migration :

Migration:
public function up()
{
   Schema::create('locations', function (Blueprint $table) {
      $table->increments('id');
      $table->integer('id_option')->unsigned();
      $table->foreign('id_option')->references('id')->on('options');
      $table->decimal('lng',11,8);
      $table->string('streetAddress1');
      $table->decimal('lat',11,8);
      $table->timestamps();
   });
}

So and we will run this migration, but we are forgot to give delete cascade on “options” table, here i mean we forgot to give like this :

$table->integer('id_option')->unsigned();
$table->foreign('id_option')->references('id')->on('options')->onDelete('cascade');

Now in “locations” table, we need added lots of records and now we want to implement delete cascade. So, we can give a delete cascade without remove any column by using DB::statement(), so here i will give you example of this :

public function up()
{
  DB::statement("ALTER TABLE locations ADD CONSTRAINT FK_locations FOREIGN KEY (id_option) REFERENCES options(id) ON DELETE CASCADE;");
}

Read Also : How to count number of files in folder and remove all files in folder in laravel example?

Thanks for read this, I hope it will you. You can also 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 →