This short article will give details on how to delete / detach the associated data in the pivot table when deleting the data in one of the associated tables.

For this example let's consider a many to many relationship between Product and Tag model entity.

If you are deleting a Tag, and you want the associations between the tag to be deleted and product be removed from the pivot table. Here is what you can do.

Here is how you can handle the deleting event in the Tag Model

class Tag extends Model
{
    protected $guarded = [];

    public function products(){
        return $this->belongsToMany('App\Product');
    }

    public static function boot() {
        parent::boot();

        static::deleting(function($tag) { // before delete() method call this
             $tag->products()->detach();
        });
    }
}

Similarly, If you are deleting a product and you want the associations between Product and Tag to be removed from the pivot table product_tag before deletion happens, Here is what you need to do.

class Product extends Model
{
    protected $guarded = [];

    public function tags(){
        return $this->belongsToMany('App\Tag');
    }

    public static function boot() {
        parent::boot();

        static::deleting(function($product) { // before delete() method call this
             $product->tags()->detach();
        });
    }
}

That's all about invoking delete event on many to many relationship in Laravel.

Comments