W
W
WebDev2016-08-23 13:14:35
Laravel
WebDev, 2016-08-23 13:14:35

Laravel event when deleting by foreign key?

Let's say there are Category and Product models. They are connected one to many.
The provider has event Product::deleted().
But it only works if you delete the product.
How to call it if the product is automatically deleted when the category is deleted?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Gavva, 2016-08-25
@aprel_co

class Category extends Eloquent
{
    public function products()
    {
        return $this->has_many('Product');
    }
    protected static function boot() {
        parent::boot();
        static::deleting(function($Category) {
             $Category->products()->delete();
        });
    }
}

Thus, before deleting a category, we first delete all products, then delete the category.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question