阅读(4344) (7)

Laravel 8 访问通知

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

一旦通知存入数据库,就需要适当的方法从通知实体访问它们。 包含在 Lareval 的默认 AppUser 模型带有 IlluminateNotificationsNotifiable trait,它的 notifications Eloquent 关联方法能返回实体通知。要获取通知,可以像其它 Eloquent 关联方法一样访问此方法。默认情况下,通知按照 created_at 时间戳排序:

$user = AppModelsUser::find(1);

foreach ($user->notifications as $notification) {
    echo $notification->type;
} 

若要只获取 「未读」通知,可以使用 unreadNotifications 关联方法。同样这些通知按照 created_at 时间戳排序::

$user = AppModelsUser::find(1);

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

技巧:若要从 JavaScript 客户端访问通知,需要为应用定义一个通知控制器,它返回可通知实体的通知,比如当前用户。可以从 JavaScript 客户端向该控制器 URI 发送 HTTP 请求。