问题
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