Laravel事件阻止更新模型

问题描述 投票:0回答:1

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

前端具有验证的逻辑,但是我也想在后端进行验证。

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

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] App\Events\ConversationSaving 
[2020-05-16 07:34:41] local.INFO: [Listener] App\Listeners\PreventMakingPrivate  
[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] App\Events\ConversationMadePrivate  
[2020-05-16 07:34:41] local.INFO: [Listener] App\Listeners\DeductCreditsForMakingPrivate  

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

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

如何防止更新?

php laravel events listener
1个回答
0
投票

哦,我明白了。如果有人也需要它,则似乎update方法成功返回1,否则不返回任何值。这解决了我的问题:

$response = $conversation->update(['user_id' => Auth::user()->id]);

if(!$response){
    return response([
        'error' => 'Error making private',
    ]);
}
© www.soinside.com 2019 - 2024. All rights reserved.