我有一個(gè)Conversation可以設(shè)置為私人的。設(shè)置為 private 意味著user_idonconversations將被分配一個(gè)非空值。如果他有足夠的積分,用戶可以將對(duì)話設(shè)置為私人。前端擁有驗(yàn)證邏輯,但我也想在后端進(jìn)行。我已將事件設(shè)置為在模型保存時(shí)觸發(fā):protected $dispatchesEvents = [ 'saving' => ConversationSaving::class,];那個(gè)事件沒什么特別的:public function __construct(Conversation $conversation){ Log::info("[Event] " . get_class()); $this->conversation = $conversation;}事件服務(wù)提供者的邏輯是這樣的:ConversationSaving::class => [ PreventMakingPrivate::class],ConversationMadePrivate::class => [ DeductCreditsForMakingPrivate::class],這個(gè)想法是觸發(fā)更新,如果更新失敗,ConversationMadePrivate事件永遠(yuǎn)不會(huì)觸發(fā)??刂破骺雌饋硐襁@樣:$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'),]);現(xiàn)在我在日志中得到的是:[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 所以代碼正確地進(jìn)入監(jiān)聽器并false從返回PreventMakingPrivate,但是模型仍然更新。我也試過設(shè)置 onConversation updating而不是saving,但同樣的事情發(fā)生了。我怎樣才能阻止更新?
1 回答

呼如林
TA貢獻(xiàn)1798條經(jīng)驗(yàn) 獲得超3個(gè)贊
哦,我明白了。如果有人也需要它,看起來update方法會(huì)在成功時(shí)返回 1,否則不會(huì)返回任何內(nèi)容。這解決了我的問題:
$response = $conversation->update(['user_id' => Auth::user()->id]);
if(!$response){
return response([
'error' => 'Error making private',
]);
}
- 1 回答
- 0 關(guān)注
- 176 瀏覽
添加回答
舉報(bào)
0/150
提交
取消