我有一个Conversation可以设置为私人的。设置为 private 意味着user_idonconversations将被分配一个非空值。如果他有足够的积分,用户可以将对话设置为私人。前端拥有验证逻辑,但我也想在后端进行。我已将事件设置为在模型保存时触发: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,但是模型仍然更新。我也试过设置 onConversation updating而不是saving,但同样的事情发生了。我怎样才能阻止更新?
1 回答
呼如林
TA贡献1798条经验 获得超3个赞
哦,我明白了。如果有人也需要它,看起来update方法会在成功时返回 1,否则不会返回任何内容。这解决了我的问题:
$response = $conversation->update(['user_id' => Auth::user()->id]);
if(!$response){
return response([
'error' => 'Error making private',
]);
}
- 1 回答
- 0 关注
- 137 浏览
添加回答
举报
0/150
提交
取消