Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: cascade soft delete

I am having offers and services table.

Service(s) is a child of an offer. So far I have established functionality for soft deleting an offer. How would I also soft delete appended services? Here is my code:

Migration Offers

Schema::create('offers', function(Blueprint $table) {     $table->increments('id')->unsigned();     ...         $table->timestamps();     $table->softDeletes(); }); 

Migration Services

Schema::create('services', function(Blueprint $table)  {     $table->increments('id');     $table->integer('offer_id')->unsigned();        ...     $table->timestamps();     $table->softDeletes(); });  Schema::table('services', function($table)  {     $table->foreign('offer_id')           ->references('id')           ->on('offers'); }); 

Model Offer

use SoftDeletes; protected $dates = ['deleted_at'];  public function services() {     return $this->hasMany('App\Service'); }  

Model Service

public function offer() {     return $this->belongsTo('App\Offer'); }  

Delete method

public function destroy($id) {     $offer = Offer::find($id);     $offer->delete(); } 

Thank you for all the help.

like image 777
be-codified Avatar asked Jul 16 '15 14:07

be-codified


People also ask

What is onDelete (' cascade ') in laravel?

The onDelete('cascade') means that when the row is deleted, it will delete all it's references and attached data too. For example if you have a User which has a Post and you set onDelete('cascade') on the user, then when the user deletes his account, all posts will be deleted as well.

How soft delete is implemented in laravel?

The feature that you are looking for is soft-deleting in Laravel. You can simply add a new database column to your Laravel Model and use the SoftDeletes trait on your model. After that,you are good to go and soft deletes work instantly.

What is soft cascade?

April 24th, 2018. Laravel Soft Cascade is a package that makes it easy to perform soft cascade deletes and restores on related models using soft deleting.


1 Answers

I have put this code in Offer model:

protected static function boot() {     parent::boot();      static::deleting(function($offer) {         $offer->services()->delete();     }); } 

And added missing

use SoftDeletes; protected $dates = ['deleted_at']; 

in the Service model.

like image 56
be-codified Avatar answered Sep 19 '22 06:09

be-codified