[英]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.