Laravel 8.x 和 9.x 的解决方案
使用 Laravel 8 变得更加容易,只需使用 saveQuietly 方法:
$user = User::find(1);
$user->name = 'John';
$user->saveQuietly();
Laravel 8.x docs
Laravel 9.x docs
Laravel 7.x、8.x 和 9.x 的解决方案
在 Laravel 7(或 8 或 9)上,按照以下方式包装您的引发事件的代码:
$user = User::withoutEvents(function () use () {
$user = User::find(1);
$user->name = 'John';
$user->save();
return $user;
});
Laravel 7.x docs
Laravel 8.x docs
Laravel 9.x docs
Laravel 5.7 到 6.x 版本的解决方案
以下解决方案适用于 Laravel 5.7 到 6.x 版本,对于旧版本,请检查答案的第二部分。
在您的模型中添加以下函数:
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 documentation
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.5 documentation