How to Add Delete Cascade to Existing Column in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel

Whenever you are making table using migration with foreign key. like i give you example as under and you forgot to set delete cascade on table then how can you add delete cascade in existing table. so let's see your 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();

});

}

and you will run this migration, but you forgot to give delete cascade on "options" table,i mean you forgot to give like this :

$table->integer('id_option')->unsigned();

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

In "locations" table, you had added lots of records and now you want to implement delete cascade. So, we can give delete cascade without remove any column using DB::statement(), i 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;");

}

Try this.........

Tags :
Shares