我有一個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 關注
- 165 瀏覽
添加回答
舉報
0/150
提交
取消