Call afterSave if a new relation was created

Hello,

I would like to remove a certain cache entry if a new relation (belongsToMany or manyToMany) entry was created on a model. So I searched for a way to perform an action after a relation entry was created / removed.

I kinda guessed it’s the afterSave() method within the Relations Model, but it’s not.

So I searched further and found this:
https://octobercms.com/docs/api/model/relation/attach

So I used this here within my Plugin’s boot method, but it also didnt work.

        Event::listen('model.relation.attach', function () {
            trace_log('hi');
        });

Did I do a mistake or am I on the wrong path?

Thanks a lot :slight_smile:

hey
you need to attach the event to your model. like this:

YourModel::extend(function ($model) {

   $model->bindEvent('model.relation.detach', function (string $relationName, $ids, array $attributes){
         });

});
2 Likes

My final solution:

    public function boot()
    {
        MyModel::extend(function ($model) {
            $model->bindEvent('model.relation.attach', function () use ($model) {
                Cache::tags('my', 'tags')->forget('name_' . $model->id);
            });
            $model->bindEvent('model.relation.detach', function () use ($model) {
                Cache::tags('my', 'tags')->forget('name_' . $model->id);
            });
        });
    }

I know I could also filter for the correct relation, but since all relations of that model should trigger the cache remove, I do not see this as necessary, or did I miss something?

Is there a reason why this have to be done via bindEvent() and why there’s no easier solution like an afterSave() method in the Model? Maybe an afterRelationChange()?

I can imagine this is a common problem if you work with relations…

1 Like