I am having offers and services table.
Service(s) is a child of an offer. So far I have established functionality for soft deletin
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.
You should use Eloquent events for this.
Offers::deleted(function($offer) {
$offer->services()->delete();
});
Offers::restored(function($offer) {
$offer->services()->withTrashed()->restore();
});
You can do like this.
self::deleting(function($offer) {
$offer->services()->delete();
});
self::restoring(function ($offer) {
$offer->services()->restore();
});
You should first delete/restore the children records (services) before deleting/restoring the parent (offer). Failing to do this, will trigger referential integrity MySql error.
If you want to get cascading softDeletes in your Eloquent Models I highly recommend using this library iatstuti/laravel-cascade-soft-deletes
// get it with composer.
$ composer require iatstuti/laravel-cascade-soft-deletes="1.0.*"
The one provided in the getting started sample.
<?php
namespace App;
use App\Comment;
use Iatstuti\Database\Support\CascadeSoftDeletes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes, CascadeSoftDeletes;
protected $cascadeDeletes = ['comments'];
protected $dates = ['deleted_at'];
public function comments()
{
return $this->hasMany(Comment::class);
}
}