Home » Php » php – Prevent action from Laravel observer events

php – Prevent action from Laravel observer events

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

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.