Laravel事件阻止更新模型



我有一个可能设置为私有的Conversation。设置为 private 意味着conversations上的user_id将被分配一个非 null 值。如果用户有足够的积分,则可以将对话设置为私人。

前端保存验证逻辑,但是我也想在后端进行验证。

我已将事件设置为在模型保存时触发:

protected $dispatchesEvents = [
'saving' => ConversationSaving::class,
];

那个事件没什么特别的:

public function __construct(Conversation $conversation)
{
Log::info("[Event] " . get_class());
$this->conversation = $conversation;
}

事件服务提供程序的逻辑捆绑如下:

ConversationSaving::class      => [
PreventMakingPrivate::class
],
ConversationMadePrivate::class => [
DeductCreditsForMakingPrivate::class
],

这个想法是触发更新,如果更新失败,ConversationMadePrivate事件永远不会触发。

控制器如下所示:

$conversation->update(['user_id' => Auth::user()->id]);
Log::info('After update');
Log::info($conversation->user_id);
Log::info($conversation->user_id ? 't':'f');
if(!$conversation->user_id){
return response([
'error' => 'Error making private',
]);
}
event(new ConversationMadePrivate($conversation));
return response([
'conversation' => $conversation->load('messages'),
]);

现在我在日志中得到的是:

[2020-05-16 07:34:41] local.INFO: [Event] AppEventsConversationSaving 
[2020-05-16 07:34:41] local.INFO: [Listener] AppListenersPreventMakingPrivate  
[2020-05-16 07:34:41] local.INFO: [Listener] Not enough credits  
[2020-05-16 07:34:41] local.INFO: After update  
[2020-05-16 07:34:41] local.INFO: 1  
[2020-05-16 07:34:41] local.INFO: t  
[2020-05-16 07:34:41] local.INFO: [Event] AppEventsConversationMadePrivate  
[2020-05-16 07:34:41] local.INFO: [Listener] AppListenersDeductCreditsForMakingPrivate  

因此,代码正确进入侦听器并从PreventMakingPrivate返回false,但是模型仍然更新。

我也尝试设置Conversationupdating而不是saving,但同样的事情发生了。

如何阻止更新?

哦,我知道了。如果有人也需要它,看起来update方法在成功时会返回 1,否则什么都没有。这解决了我的问题:

$response = $conversation->update(['user_id' => Auth::user()->id]);
if(!$response){
return response([
'error' => 'Error making private',
]);
}

最新更新