防止Laravel观察者事件采取行动 [英] 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']);
在观察者中
public function updating(Model $model)
{
if($model->isDirty('foo') {
// Prevent action from happening
}
}
谢谢.
推荐答案
您可以简单地返回false.
You can simply return false.
如文档中所述. http://laravel.com/docs/5.6/events#defining-listeners.
有时,您可能希望停止将事件传播到其他侦听器.您可以通过从侦听器的handle方法返回false来实现.
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;
}
}
尽管模型实例值已更新,但数据库中未更新这些实例值,所以请注意将实例返回到视图或API时.要解决此问题,您可以使用 getOriginal()
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()
希望这会有所帮助.
这篇关于防止Laravel观察者事件采取行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!