标记为阅读laravel中的特定通知5.3通知

时间:2016-09-05 11:15:49

标签: php laravel laravel-5.3

我知道有很多方法可以标记为读取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标记的data-notif-id属性都包含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模型,我怎么能这样做?

5 个答案:

答案 0 :(得分:5)

这一切都有效:

$id = auth()->user()->unreadNotifications[0]->id;
auth()->user()->unreadNotifications->where('id', $id)->markAsRead();

答案 1 :(得分:4)

根据Github上的this Answer,解决方案是:

  

Illuminate\Notifications\DatabaseNotification是模型的所在   通知存在,您可以使用它来通过ID获取通知   并删除它。此外,如果您不想使用该模型,您可以使用   正常的数据库查询。

答案 2 :(得分:3)

$notification = auth()->user()->notifications()->find($notificationid);
if($notification) {
    $notification->markAsRead();
}

答案 3 :(得分:1)

您必须首先确保该通知首先存在,以便您可以对其进行调整,我不建议您使用unreadNotifications对象,因为如果没有未读通知,则会因此而发生错误

var parts = input.split(' ');

或者您可以直接编辑而无需任何检查

$notification_id = "03fac369-2f41-43d0-bccb-e364aa645f8a";
$Notification = Auth::user()->Notifications->find($notification_id);
if($Notification){
   $Notification->markAsRead();
}

答案 4 :(得分:0)

代替以下内容:

$user->unreadNotifications->markAsRead(); 

让我们使用:

$user->unreadNotifications->first()->markAsRead();