Laravel fire obeserver on pivot relations

firing observer pivot
Share on facebook
Share on twitter
Share on linkedin

While I was working on cleanup of backend controller, and moving some of the logic from controller to observer, I found myself in situation where observer is not getting triggered because model by itself didn’t have any update on it’s properties.

That was the case when user updated only parts which belong to relations of that model, and it got me in position where part of code which I moved to observer, was not executed in mentioned cases.

Firing model event ‘update’ manually was not clear solution, as then it would be triggered twice if there were actual changes on the model properties (not a big problem until you start listening for it elsewhere, or using logs package…).

As I was considering usage of laravel-pivot package, which is suggested solution to this problem on forums, I came up to following idea:

In your model, add custom observable event:

Then create new models function which would behave as regular save()

but will also trigger custom model event customUpdate which we signed already.

Next step that you need to do is to go to observer class which you created at first until you came into similar problem as I did, and write down new function:

And from that point, you are free to handle data via services in that observer.

3 2 votes
Article Rating

Subscribe to our newsletter

Be first to read new helpful post

Share this post with your friends

Share on linkedin
Share on xing
Share on twitter
Share on facebook
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Krishan
12 days ago

I’d be interested in seeing some of the code you moved to the Observer and find out why you moved it there. You mention yourself that it does not directly rely on the model’s properties being updated, which is an indication that the code might not belong in that specific Observer.