阅读(3539) (7)

Laravel 8 标记通知已读

2021-07-06 09:24:54 更新

通常,在用户阅览一条通知之后,你会想将其标识为「已读」。 IlluminateNotificationsNotifiable trait 提供了 markAsRead 方法,它更新数据库中通知记录的 read_at 列:

$user = AppModelsUser::find(1);

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

当然,您亦可在通知集合上使用 markAsRead 方法来代替遍历通知:

$user->unreadNotifications->markAsRead(); 

您亦可通过大规模更新查询(不指定 where 条件的更新)来将所有通知标记为已读,而不必将其从数据库检索出来:

$user = AppModelsUser::find(1);

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

您也可以使用 delete 方法来将其从数据库实体中删除:

$user->notifications()->delete();