Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent action from Laravel observer events

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.

like image 894
Asur Avatar asked Apr 25 '18 07:04

Asur


1 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.

like image 183
Romantic Dev Avatar answered Oct 24 '22 07:10

Romantic Dev