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

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

问题描述

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

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

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

所以每次保存模型时,我都会收到一条消息通知用户.问题是,有时我只需要更新状态"之类的字段或增加计数器",而我不需要为此发送消息.那么,是否可以暂时禁用触发模型事件?或者是否有像 $model->save() 这样的 Eloquent 方法不会触发已保存"事件?

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?

推荐答案

Laravel 8.x 解决方案

使用 Laravel 8 变得更加容易,只需使用 saveQuietly 方法:

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

$user->saveQuietly();

Laravel 8 文档

在 Laravel 7(或 8)上,按照以下方式包装您的引发事件的代码:

On Laravel 7 (or 8) wrap your code that throws events as per below:

$user = User::withoutEvents(function () use () {
    $user = User::find(1);
    $user->name = 'John';
    $user->save();

    return $user;
});

Laravel 7.x 文档
Laravel 8.x 文档

以下解决方案适用于 Laravel 5.7 到 6.x 版本,对于旧版本,请检查答案的第二部分.

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

有关更多信息,请查看 Laravel 6.x 文档

For more info check the Laravel 6.x documentation

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

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

有关更多信息,请查看 Laravel 5.6 文档

For more info check the Laravel 5.6 documentation

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

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