Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 Cascading Soft Deletes

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.

like image 792
Rob W Avatar asked Jun 21 '13 20:06

Rob W


1 Answers

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();
            }
        });
    }
like image 83
robjmills Avatar answered Oct 15 '22 22:10

robjmills