2016-09-05 34 views
2

我知道,有很多方法可以標記爲已讀的用戶的所有通知在L5.3這樣的:馬克在laravel 5.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屬性包含通知符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模型?

+0

如果沒有'Notification'模型(所以,沒有關係集),其中確實來自'unreadNotifications'方法?或者:它是什麼?自定義方法? – lesssugar

+0

'Illuminate \ Notifications \ Notifiable'特徵提供了一個'markAsRead'方法,我在用戶模型中使用它。 –

+0

'unreadNotifications()'返回一個模型,因此可以使用鏈接來過濾,就像這樣:'$ user-> unreadNotifications() - > where('notifications.id',$ id) - > markAsRead(); '。或者,如果'markAsRead()'方法不可用,我也會嘗試使用' - > update(['read_at'=> Carbon :: now()])''。 – lesssugar

回答

1

this Answer在Github上,解決辦法是:

Illuminate\Notifications\DatabaseNotification就是存在 通知的型號,你可以用它來抓取通過ID 通知並刪除它。另外,如果您不想使用該模型,則可以使用正常的數據庫查詢 。

0

這工作沒有失敗:

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