2016-09-05 4 views
2

私は、このよう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 NOTIF data-notif-id属性含まれています見ての通り。

今、このIDをAjax(クリックイベント)を介してスクリプトに送信し、その通知のみを読むようにマークします。そのために私はこれを書いた:

$('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モデルが存在しない間ことを行うことができますか?

+0

なし 'Notification'モデル(そう、関係ないセットが)がない場合は、どこ' unreadNotifications'方法はから来たのでしょうか?または:それは何ですか?カスタムメソッド? – lesssugar

+0

'Illuminate \ Notifications \ Notifiable'特性は' markAsRead'メソッドを提供し、私はこれをUser Modelで使用しました。 –

+0

'unreadNotifications()'はモデルを返しますので、チェーンを使ってフィルタリングすることができます: '$ user-> unreadNotifications() - >( 'notifications.id'、$ id) - > markAsRead(); '。 'markAsRead()'メソッドが利用できない場合は、代わりに ' - > update(['read_at' => Carbon :: now()])'を使ってみてください。 – lesssugar

答えて

1

はGithubの上this Answerによると、解決策は次のとおりです。

Illuminate\Notifications\DatabaseNotificationは 通知のモデルが存在する場合、あなたはID による通知を取得し、それを削除するために使用することができます。また、モデルを使用したくない場合は、通常のDBクエリ を使用することができます。

0

これは失敗せずに動作します:

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