Laravel

Laravel fire obeserver on pivot relations

Max Hutschenreiter -

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

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

Firing model event ‘update’ manually was no 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 the usage of laravel-pivot package, which is the suggested solution to this problem on forums, I came up to the following idea:

In your model, add a custom observable event:
    /**
     * Array of our custom model events declared under model property $observables
     * @var array
     */
 
    protected $observables = [
        'customUpdate',
    ];
Then create new models function which would behave as regular save()
    public function customSave()
    {
        $this->fireModelEvent('customUpdate', false);
        $this->save();
    }
but will also trigger custom model event customUpdate which we signed already.

The next step that you need to do is to go to observer class which you created at first until you came into a similar problem as I did, and write down a new function:
public function customUpdate(Model $model)
And from that point, you are free to handle data via services in that observer.

Tags: Laravel · firing event · Observer · Pivot

Want products news and updates?

Sign up for our newsletter to stay up to date.

We care about the protection of your data. Read our Privacy Policy.

Impressions from our Team

  • Happy birthday 🎁🎈🎂 Filip - #

  • Another day another #mandarinacakeshop 🎂 😀 - #

  • Happy Birthday Ognjen! And marry Christmas to all other 🎄#notacakeshop - #

  • #Office #Garden - #

  • #workhard - #

  • #belgrade #skyline - #

  • #happybirthday Phil :) - #

  • #happybirthday Stefan 🥂 - #

  • #happybirthday Lidija 🍾 - #

  • Say hi 👋 to our newest team member ☕️ - #

  • #bithday #cake 😻 - #

  • #stayathome #homeoffice #42coders - #

  • #stayathome #homeoffice #42coders #starwars :) - #

  • #stayathome #homeoffice #42coders - #

  • We had a really nice time with #laracononline #laravel - #

  • Happy Birthday 🎂 Miloš - #

  • Happy Birthday 🎂Nikola - #

  • #42coders #christmas #dinner what a nice evening :) - #

  • Happy Birthday 🎂 Ognjen - #

  • Wish you all a merry Christmas 🎄🎁 - #

See more!

© 2024 42coders All rights reserved.