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.