Cascading deletes with model events

Submitted by robjmills - 10 years ago

If you're not making use of MySQL InnoDB cascades, you might still want to cause events (such as deleting) on related models to cascade. The example below listens for the deleted event on the Product model and cascades this to the child models.

class Product extends Eloquent{
    
    public function descriptions()
    {
        return $this->hasMany('Description');
    }

    public function images()
    {
        return $this->hasMany('Image');
    }
    
    // .....
    
    public static function boot()
    {
        parent::boot();    
    
        // cause a delete of a product to cascade to children so they are also deleted
        static::deleted(function($product)
        {
            $product->images()->delete();
            $product->descriptions()->delete();
        });
    }    
}