ItSolutionStuff.com

How to Add Delete Cascade to Existing Column in Laravel?

By Hardik Savani • November 5, 2023
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: Laravel
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Migration Default Value Current Timestamp Example

Read Now →

How to Create Migration in Laravel 9?

Read Now →

How to Run Migration and Seeder on Laravel Vapor?

Read Now →

How to Change Column Length using Laravel Migration?

Read Now →

How to Update Enum Value in Laravel Migration?

Read Now →

Laravel Migration Enum Default Value Example

Read Now →

How to Add Index in Laravel Migration?

Read Now →

How to Add Foreign Key in Laravel Migration?

Read Now →

Laravel Migration - How to Add New Column in Existing Table ?

Read Now →

How to Change Table Name using Laravel Migration?

Read Now →

How to Remove Column from Table in Laravel Migration?

Read Now →

How to Change Column Name and Data Type in Laravel Migration?

Read Now →

How to Create Table using Migration in Laravel?

Read Now →

How to Drop Foreign Key Constraint in Laravel Migration?

Read Now →