Laravel observer for pivot table

Viewed 7323

I've got a observer that has a update method:

ObserverServiceProvider.php

public function boot()
{
    Relation::observe(RelationObserver::class);
}

RelationObserver.php

public function updated(Relation $relation)
{
    $this->cache->tags(Relation::class)->flush();
}

So when I update a relation in my controller:

public function update(Request $request, Relation $relation)
{
     $relation->update($request->all()));
     return back();
}

Everything is working as expected. But now I've got a pivot table. A relation belongsToMany products.

So now my controller method looks like this:

public function update(Request $request, Relation $relation)
{
    if(empty($request->products)) {
        $relation->products()->detach();
    } else {
        $relation->products()->sync(collect($request->products)->pluck('id'));
    }

    $relation->update($request->all());

    return back();
}

The problem is that the observer is not triggered anymore if I only add or remove products.

How can I trigger the observer when the pivot table updates aswel?

Thanks

3 Answers

When I search about this topic, it came as the first result. However, for newer Laravel version you can just make a "Pivot" model class for that.

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\Pivot;

class PostTag extends Pivot
{
    protected $table = 'post_tag';

    public $timestamps = null;
}

For the related model

public function tags(): BelongsToMany
{
    return $this->belongsToMany(Tag::class)->using(PostTag::class);
}

and you have to put your declare your observer in EventServiceProvider as stated in Laravel Docs

PostTag::observe(PostTagObserver::class);

Reference: Observe pivot tables in Laravel

Just add:

public $afterCommit = true;

at the beginning of the observer class.. It will wait until the transactions are done, then performs your sync which should then work fine..

Please check Laravel's documentation for that.

It seems this solutions was just added in Laravel 8.

Related