我知道在L5.3中有很多方法可以标记所有用户通知为已读,例如:
$user = App\User::find(1);
foreach ($user->unreadNotifications as $notification) {
$notification->markAsRead();
}
或者:
$user->unreadNotifications->markAsRead();
但是假设我想要标记一个特定ID的通知为已读。
实际上,我已经按照以下方式列出了未读用户通知:
<ul class="menu">
@foreach($AuthUser->unreadNotifications as $notif)
<li>
<a href="{{$notif->data['action']}}" data-notif-id="{{$notif->id}}">
{{$notif->data['message']}}
</a>
</li>
@endforeach
</ul>
正如您所看到的,每个a
标签都有一个包含通知ID的data-notif-id
属性。
现在我想通过Ajax将此ID发送到脚本(在单击事件中),并仅将该通知标记为已读。为此,我编写了以下代码:
$('a[data-notif-id]').click(function () {
var notif_id = $(this).data('notifId');
var targetHref = $(this).data('href');
$.post('/NotifMarkAsRead', {'notif_id': notif_id}, function (data) {
data.success ? (window.location.href = targetHref) : false;
}, 'json');
return false;
});
NotifMarkAsRead
指的是以下控制器:
class NotificationController extends Controller
{
public function MarkAsRead (Request $request)
{
//What Do I do Here........
}
}
如果没有任何Notification
模型,我该如何做到这一点?
Notification
模型(因此没有关系集),那么unreadNotifications
方法来自哪里?或者说:它是什么?一个自定义方法吗? - lesssugarIlluminate\Notifications\Notifiable
特性提供了一个markAsRead
方法,我在User Model中使用了它。 - Ahmad BadpeyunreadNotifications()
返回一个模型,因此您可以使用链接来过滤,例如:$user->unreadNotifications()->where('notifications.id', $id)->markAsRead();
。或者,如果markAsRead()
方法不可用,我也会尝试使用->update(['read_at' => Carbon::now()])
来代替。 - lesssugar