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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With