How to Add Delete Cascade to Existing Column in 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.........
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Migration Default Value Current Timestamp Example
- How to Create Migration in Laravel 9?
- How to Run Migration and Seeder on Laravel Vapor?
- How to Change Column Length using Laravel Migration?
- How to Update Enum Value in Laravel Migration?
- Laravel Migration Enum Default Value Example
- How to Add Index in Laravel Migration?
- How to Add Foreign Key in Laravel Migration?
- Laravel Migration - How to Add New Column in Existing Table ?
- How to Change Table Name using Laravel Migration?
- How to Remove Column from Table in Laravel Migration?
- How to Change Column Name and Data Type in Laravel Migration?
- How to Create Table using Migration in Laravel?
- How to Drop Foreign Key Constraint in Laravel Migration?