是否有可能暂时禁用Laravel中的事件?

问题描述 投票:6回答:5

我在'已保存'模型事件中有以下代码:

Session::flash('info', 'Data has been saved.')` 

因此,每次保存模型时,我都可以通过flash消息通知用户。问题是,有时我只需更新像'status'这样的字段或增加'计数器'而我不需要flash消息。那么,是否可以暂时禁用触发模型事件?或者有没有像$model->save()这样的Eloquent方法不会触发'已保存'事件?

laravel laravel-4
5个回答
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


9
投票

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();

非常优雅和简单:)


7
投票

调用模型Object然后调用unsetEventDispatcher之后,您可以执行任何操作,而无需担心事件触发

像这个:

    $IncidentModel = new Incident;
    $IncidentModel->unsetEventDispatcher();

    $incident = $IncidentModel->create($data);

3
投票

您不应该将会话闪存与模型事件混合在一起 - 当事情发生时,模型不负责通知会话。

控制器在保存模型时调用会话闪存会更好。

这样您就可以控制何时实际显示消息 - 从而解决您的问题。


3
投票

要为最终在此寻找解决方案的任何人回答问题,您可以使用unsetEventDispatcher()方法禁用实例上的模型侦听器:

$flight = App\Flight::create(['name' => 'Flight 10']);
$flight->unsetEventDispatcher();
$flight->save(); // Listeners won't be triggered
© www.soinside.com 2019 - 2024. All rights reserved.