是否可以暂时禁用Laravel中的事件? [英] Is it possible to temporarily disable event in Laravel?

查看:148
本文介绍了是否可以暂时禁用Laravel中的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

因此,每次保存模型时,我都会有一条简短的消息通知用户.问题是,有时我只需要更新状态"之类的字段或增加计数器"之类的字段,而我不需要即时消息.因此,是否可以暂时禁用触发模型事件?还是有任何雄辩的方法,例如$model->save(),不会触发保存"事件?

解决方案

以下解决方案从Laravel版本5.7到6.x 有效,对于较旧的版本,请检查答案的第二部分. /p>

在模型中添加以下功能:

public function saveWithoutEvents(array $options=[])
{
    return static::withoutEvents(function() use ($options) {
        return $this->save($options);
    });
}

然后进行保存而不发生任何事件,如下所示:

$user = User::find(1);
$user->name = 'John';

$user->saveWithoutEvents();

有关更多信息,请参见 Laravel 6. x文档


以下解决方案适用于 Laravel 5.6和更低版本.

在Laravel 5.6(及以前的版本)中,您可以禁用并再次启用事件观察器:

// 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 5.6文档

I have the following code in 'saved' model event:

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

so everytime the model is saved I can have a flash message to inform users. The problem is, sometimes I just need to update a field like 'status' or increment a 'counter' and I don't need a flash message for this. So, is it possible to temporarily disable triggering the model event? Or is there any Eloquent method like $model->save() that doesn't trigger 'saved' event?

解决方案

The following solution works from the Laravel version 5.7 to 6.x, for older versions check the second part of the answer.

In your model add the following function:

public function saveWithoutEvents(array $options=[])
{
    return static::withoutEvents(function() use ($options) {
        return $this->save($options);
    });
}

Then to save without events proceed as follow:

$user = User::find(1);
$user->name = 'John';

$user->saveWithoutEvents();

For more info check the Laravel 6.x documentation


The following solution works for Laravel 5.6 and older versions.

In Laravel 5.6 (and previous versions) you can disable and enable again the event observer:

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

For more info check the Laravel 5.6 documentation

这篇关于是否可以暂时禁用Laravel中的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆