Laravel 8 標(biāo)記通知已讀

2021-07-19 10:55 更新

通常,在用戶閱覽一條通知之后,你會想將其標(biāo)識為「已讀」。 Illuminate\Notifications\Notifiable trait 提供了 markAsRead 方法,它更新數(shù)據(jù)庫中通知記錄的 read_at 列:

$user = App\Models\User::find(1);

foreach ($user->unreadNotifications as $notification) {
    $notification->markAsRead();
} 

當(dāng)然,您亦可在通知集合上使用 markAsRead 方法來代替遍歷通知:

$user->unreadNotifications->markAsRead(); 

您亦可通過大規(guī)模更新查詢(不指定 where 條件的更新)來將所有通知標(biāo)記為已讀,而不必將其從數(shù)據(jù)庫檢索出來:

$user = App\Models\User::find(1);

$user->unreadNotifications()->update(['read_at' => now()]); 

您也可以使用 delete 方法來將其從數(shù)據(jù)庫實體中刪除:

$user->notifications()->delete(); 
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號