Is there a modular way to perform cascading soft deletes in L4?
My database is already designed to do this with hard deletes because all tables are related to another.. however, I'm using soft deletes and really do not want to have to overload the delete()
method in my models - simply due to (A) the amount of models, and (B) having to edit the delete()
method in all models when other models change.
Any pointers or tips would be appreciated.
I do know this is possible from within my models:
public function delete() {
ChildTable::where('parent_id', $this->id)->delete();
ChildTable2::where('parent_id', $this->id)->delete();
parent::delete();
}
But any update to models or table structure would cause this to be appended/edited.. including other models.
I've got cascading deletes working using model events, for example in a Product model I bind to the deleted event so I can soft-delete all relations:
// Laravel's equivalent to calling the constructor on a model
public static function boot()
{
// make the parent (Eloquent) boot method run
parent::boot();
// cause a soft delete of a product to cascade to children so they are also soft deleted
static::deleted(function($product)
{
$product->images()->delete();
$product->descriptions()->delete();
foreach($product->variants as $variant)
{
$variant->options()->delete();
$variant->delete();
}
});
}