我在'已保存'模型事件中有以下代码:
Session::flash('info', 'Data has been saved.')`
所以每次保存模型时我都会有一条flash消息通知用户。问题是,有时我只需更新像'status'这样的字段或增加'计数器'而我不需要flash消息。那么,是否可以暂时禁用触发模型事件?或者是否有像$model->save()
这样的Eloquent方法不会触发“已保存”事件?
答案 0 :(得分:16)
在这里您可以了解如何禁用并再次启用事件观察器:
// getting the dispatcher instance (needed to enable again the event observer later on)
$dispatcher = YourModel::getEventDispatcher();
// disabling the events
YourModel::unsetEventDispatcher();
// perform the operation you want
$yourInstance->save();
// enabling the event dispatcher
YourModel::setEventDispatcher($dispatcher);
有关更多信息,请检查Laravel documentation
答案 1 :(得分:8)
泰勒(Taylor)的Twitter页面上有一个不错的解决方案:
将此方法添加到基本模型中,或者如果没有该方法,请创建一个特征或将其添加到当前模型中
public function saveQuietly(array $options = [])
{
return static::withoutEvents(function () use ($options) {
return $this->save($options);
});
}
然后在您的代码中,每当需要保存模型而不会触发事件时,只需使用以下代码即可:
$model->foo = 'foo';
$model->bar = 'bar';
$model->saveQuietly();
非常优雅和简单:)
答案 2 :(得分:7)
调用模型Object然后调用unsetEventDispatcher 之后,你可以做任何你想做的事情而不用担心事件触发
像这样: $IncidentModel = new Incident;
$IncidentModel->unsetEventDispatcher();
$incident = $IncidentModel->create($data);
答案 3 :(得分:3)
你不应该将会话闪烁与模型事件混合在一起 - 当事情发生时,模型不负责通知会话。
控制器在保存模型时调用会话闪存会更好。
通过这种方式,您可以控制何时实际显示消息 - 从而解决您的问题。
答案 4 :(得分:2)
要回答最终在此寻找解决方案的任何人的问题,您可以使用unsetEventDispatcher()
方法在实例上禁用模型侦听器:
$flight = App\Flight::create(['name' => 'Flight 10']);
$flight->unsetEventDispatcher();
$flight->save(); // Listeners won't be triggered
答案 5 :(得分:2)
在laravel 7.x中,您可以轻松做到
use App\User;
$user = User::withoutEvents(function () use () {
User::findOrFail(1)->delete();
return User::find(2);
});
中查看更多
答案 6 :(得分:1)
在laravel 8.x中:
保存没有事件的单个模型
有时您可能希望在不引发任何事件的情况下“保存”给定的模型。您可以使用saveQuietly方法完成此操作:
$user = User::findOrFail(1);
$user->name = 'Victoria Faith';
$user->saveQuietly();