删除模型后如何触发Laravel(5.6)事件? [英] How to fire Laravel (5.6) Event when Model is deleted?

查看:147
本文介绍了删除模型后如何触发Laravel(5.6)事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从系统中删除用户时触发事件,但我认为它删除用户的速度过快,因此我的事件无法正常工作.我要做的是删除用户后的广播.

I'm trying to fire an Event when a User is deleted from the system but I'm thinking it's deleting my user too quickly so my Event isn't working. What I'm looking to do is broadcast when a User is deleted.

这里是控制器:

public function destroy($id)
{
    $user = new User();

    $user = $user->find($id);

    broadcast(new UserWasDeleted($user, Auth::user()))->toOthers();

    $user->delete();

    return response([
                        'status'  => 'success',
                        'message' => 'The user was successfully deleted.'
                    ], 200);
}

如果删除$ user-> delete(),此广播将成功广播;线路,并且在那里时不会广播.

This successfully broadcasts if I remove the $user->delete(); line, and doesn't broadcast when it is in there.

我什至尝试为事件设置侦听器,并在侦听器中删除用户.它删除了用户,但仍然不广播.

I've even tried setting up a Listener for the Event, and deleting the User in the Listener. It deletes the user, but still does no broadcasting.

推荐答案

需要从处理已删除模型的事件中删除SerializesModels特性.

The SerializesModels trait needs to be removed from events that deal with deleted models.

SerializesModels是一个特征,它仅在序列化事件(或作业)时存储模型的ID,而在未序列化事件时从数据库中重新获取模型.

SerializesModels is a trait that only stores the id of the model when the event (or job) is serialized, and refetches the model from the database when the event is unserialized.

这允许排队的进程在运行时从数据库中获取新模型,因此它们不会使用过时的信息运行,但是当您从数据库中删除该行时,这将是不可靠的.

This allows queued processes to get a fresh model from the database when they run so they are not running with outdated information, but this would not be reliable when you're deleting that row from the database.

这篇关于删除模型后如何触发Laravel(5.6)事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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