Search code examples
laravellaravel-8observer-patternobservers

Laravel Observer Updating/Updated


I am not sure how best to do this. I need access to is_dirty() to check if specific fields were changed which needs to be done in the 'Updating' method in the observer. But I only want to act on it if the update is successful.

If there a way within the 'Updating' method to tell it to try to save the changes and then see if it was successful?

If not, what would be the best way to pair Updating and Updated? Would I just save a cache value in Updating specifying if the relevant fields were modified, then pull that cache value in Updated? Or would there be a better way?


Solution

  • You could try something along these lines:

    class ModelObserver
    {   
        public function updated(Model $model)
        {
            /**
             * Listening inside 'updated' since we only care about model 
             * updated which have already happened
             */
            if ($model->wasChanged('my-special-field')) {
                // Do something...
            } 
        }
    }
    

    You can read more about the wasChanged method here.