[英]How to paginate Laravel 5.3 database Notifications
我們知道Laravel 5.3中的Notifications可以通過多個渠道發送,並可以存儲在數據庫中。
我們知道可以獲取用戶的所有通知並顯示如下:
$user = App\User::find(1);
foreach ($user->notifications as $notification) {
echo $notification->type;
}
但假設我有一個AllNotifications頁面,顯示用戶的所有通知,我想分頁。
有沒有辦法分頁通知?
更新:
據GitHub上themsaid答案我試過的代碼:
您可以使用$ user-> notifications() - > paginate(),HasDatabaseNotifications特性具有常規的morphMany關系。
第一個問題已經解決但是又出現了另一個問題。
我有三個notif並使用$user->notifications()->paginate(2)
,然后頁面鏈接顯示在第一頁但它沒有顯示在第二頁,在這種情況下我無法導航到其他頁面。 為什么?
注意:我發現上面的問題不在Laravel 5.3.4中,但在5.3.6中有
嘗試這個:
$page = 2; /* Actual page */
$limit = 4; /* Limit per page*/
\Auth::user()->notifications()->offset($page*$limit)->limit($limit)->get();
我在V 5.5中嘗試這個。*它對我有用:
$perpage = $request->input('perpage', 15);
$page = $request->input('page', 1);
return $user->notifications()->paginate($perpage, ['*'], 'page', $page);
結果:
"data": [],
"links": {
"first": "http://domain.test/notification?page=1",
"last": "http://domain.test/notification?page=2",
"prev": "http://domain.test/notification?page=1",
"next": null
},
"meta": {
"current_page": 2,
"from": 4,
"last_page": 2,
"path": "http://domain.test/notification",
"per_page": "3",
"to": 4,
"total": 4,
}
額外:如果您要添加未讀Eloquent:API資源
$notification = $user->notifications()->paginate($perpage, ['*'], 'page', $page);
return NotificationResource::collection($notification)->additional(['meta' => [
'unread' => $user->unReadNotifications->count(),
]]);
結果:
"data": [],
"links": {},
{
"meta": {
"current_page": 2,
"from": 4,
"last_page": 2,
"path": "http://domain.test/notification",
"per_page": "3",
"to": 4,
"total": 4,
"unread": 4 // here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.