Reputation: 6612
We know that Notifications in Laravel 5.3 can sent via many channels and can store in database.
And we know that can fetch all notifications of a User and show them like this :
$user = App\User::find(1);
foreach ($user->notifications as $notification) {
echo $notification->type;
}
But Suppose case that I have a AllNotifications page that show all notifications of a user and I want to paginate that.
Is there any way to paginate notifications ?
Update:
According to themsaid answer on github I tried the code :
You can use $user->notifications()->paginate(), the HasDatabaseNotifications trait has a regular morphMany relationship.
First problem is solved But another problem is occured.
I have three notif and used $user->notifications()->paginate(2)
, then pages links show on the first page but it does not show in the second page and in this case I could not navigate to other pages. why?
Note: I found that above problem is not in Laravel 5.3.4 But there is in 5.3.6
Upvotes: 3
Views: 3516
Reputation: 139
I try this in V 5.5.* it work for me:
$perpage = $request->input('perpage', 15);
$page = $request->input('page', 1);
return $user->notifications()->paginate($perpage, ['*'], 'page', $page);
Result:
"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,
}
Extra: if you want to add Unread Eloquent: API Resources
$notification = $user->notifications()->paginate($perpage, ['*'], 'page', $page);
return NotificationResource::collection($notification)->additional(['meta' => [
'unread' => $user->unReadNotifications->count(),
]]);
Result:
"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
}
Upvotes: 1
Reputation: 317
Try this:
$page = 2; /* Actual page */
$limit = 4; /* Limit per page*/
\Auth::user()->notifications()->offset($page*$limit)->limit($limit)->get();
Upvotes: 4