Prevent action from Laravel observer events

生来就可爱ヽ(ⅴ<●) 提交于 2020-06-27 07:55:21

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/50016476/prevent-action-from-laravel-observer-events

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!