取消事件触发

有时候你的操作可能会触发别人的事件(也不知道是哪个大佬写的,咱也不敢乱改)
分享一个取消事件的例子。

//获取model里面的事件
$dispatcher = YourModel::getEventDispatcher();

//禁用model里面的事件
YourModel::unsetEventDispatcher();

// 调用model的save方法
$yourInstance->save();

//启用事件
YourModel::setEventDispatcher($dispatcher);
//Visitor model有saved事件,某些地方某些情况监听到后做一些其他操作
protected $dispatchesEvents = [
        'saved' => VisitorSavedEvent::class,
    ];
//有时候不需要触发事件,是可以取消的,可以调用model的update方法避开save()或者取消事件(推荐后者)。
// 获取来访信息
        $visitor = Visitor::where('id', $request->visitor_id)->first();
//取消事件触发
$dispatcher = Visitor::getEventDispatcher();
Visitor::unsetEventDispatcher();
$ret = $visitor->save();
Visitor::setEventDispatcher($dispatcher);

参考链接:

https://stackoverflow.com/questions/294078...

本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 4年前 自动加精
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 4
YourModel::withoutEvents(function(){
     // do something...
});
4年前 评论
Rekkles 4年前
jake666 4年前
XiaohuiLam 4年前
Yoger (楼主) 4年前
Mumujin 4年前
Yoger (楼主) 4年前
YourModel::withoutEvents(function(){
     // do something...
});
4年前 评论
Rekkles 4年前
jake666 4年前
XiaohuiLam 4年前
Yoger (楼主) 4年前
Mumujin 4年前
Yoger (楼主) 4年前
houmuxu

Test::withoutEvents(function(){
// do something...
});
这个执行报Illuminate\Database\Query\Builder::withoutEvents does not exist.
是我版本过低吗,5.5的

4年前 评论
Yoger (楼主) 4年前

withoutEvents方法在vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasEvents.php
源码如下:

 public static function withoutEvents(callable $callback)
    {
        $dispatcher = static::getEventDispatcher();
        static::unsetEventDispatcher();
        try {
            return $callback();
        } finally {
            if ($dispatcher) {
                static::setEventDispatcher($dispatcher);
            }
        }
    }
4年前 评论
sanders

我觉得如果这样写了,一般事件触发的时机或监听器设置就存在问题了。

4年前 评论
Yoger (楼主) 4年前
sanders (作者) 4年前
Yoger (楼主) 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!