首页 > 解决方案 > 将单个 Laravel 通知标记为已读

问题描述

我的应用程序中有一个页面,其中显示了用户当前拥有的所有未读通知的列表,并且每个通知都有一个已读图标。

数据库中的 ID 设置为char一长串字母和数字。当我在页面上显示通知的 ID 时,它们都返回与数据库中的内容毫无关系的数字,因此当我运行查询以读取通知时,它找不到 ID,因为 ID 不是t 匹配。

在 Laravel 中读取单个通知的最佳方法是什么?我正在使用下面的代码进行尝试,但这$request->get('id')是不正确的,因为我似乎将 12310 作为 ID,其中一些甚至是 0。

Auth::user()->unreadNotifications->where('id', $request->get('id'))->markAsRead()

标签: phplaravel

解决方案


Laravelnotificationsid用作CHAR默认字段类型。因此,当您过滤某些 id 时,您必须使用first()如下方式。由于unreadNotificationsIlluminate\Notifications\DatabaseNotificationCollection

$notificationId = request('notification_id');

$userUnreadNotification = auth()->user()
                            ->unreadNotifications
                            ->where('id', $notificationId)
                            ->first();

if($userUnreadNotification) {
    $userUnreadNotification->markAsRead();
}

推荐阅读