9

I would like to know how an action could be prevented on a model observer, for example:

$model->update(['foo' => 'bar']);

In the observer

public function updating(Model $model)
{
    if($model->isDirty('foo') {
        // Prevent action from happening
    }
}

Thank you in advance.

Asur
  • 2,950
  • 1
  • 19
  • 31

1 Answers1

14

You can simply return false.

As mentioned in the docs. http://laravel.com/docs/5.6/events#defining-listeners.

Sometimes, you may wish to stop the propagation of an event to other listeners. You may do so by returning false from your listener's handle method.

this action will not be updating the record/model.

public function updating(Model $model)
{
    if ($model->isDirty('foo')) {
       // Prevent action from happening
       return false;
    }
}

Although model instance values gets updated but these are not updated in database so beware while returning the instance to views or APIs. To cater this problem you can use getOriginal()

Hope this helps.

sta
  • 8,667
  • 4
  • 29
  • 47
Adnan Mumtaz
  • 12,573
  • 5
  • 32
  • 59
  • That's so simple, but i didn't find it anywhere, do you know any resource where this is mentioned? Thank you very much – Asur Apr 25 '18 at 07:38
  • @Asur If you dig into source you will find one. :D – Adnan Mumtaz Apr 25 '18 at 07:49
  • @Asur although model instance values gets updated but these are not updated in database so beware while returning the instance to views or APIs – Adnan Mumtaz Apr 25 '18 at 07:51
  • You can check it [here](https://laravel.com/api/5.6/Illuminate/Database/Eloquent/Model.html#method_getOriginal) – Asur Apr 25 '18 at 07:55
  • This is mentioned in the docs @ https://laravel.com/docs/5.6/events#defining-listeners. `Stopping The Propagation Of An Event - Sometimes, you may wish to stop the propagation of an event to other listeners. You may do so by returning false from your listener's handle method.` – Robert Apr 25 '18 at 08:04