Reputation: 21
I have two queries:
$posts = Post::all();
$comments = Comment:all();
Which I later merge:
$merge = $posts->merge($comments);
$all = $merge->sortByDesc(function($result) {
return $result->created_at;
});
How can I paginate the result of the merge? Doing $all->paginate(25)
does not work.
Upvotes: 2
Views: 968
Reputation: 1202
Laravel 5:
You can use spatie/laravel-collection-macros.
$posts = Post::all();
$comments = Comment:all();
return $comments->merge($posts)->paginate();
Upvotes: 0
Reputation: 146191
You may try this (Version-5x
):
// Add this at the top of your class
use Illuminate\Pagination\LengthAwarePaginator as Paginator;
// Then use following code:
$perPage = 10;
$currentPage = app('request')->get('page') ?: 1; // or $request->get('page') if available
$paginator = new Paginator($all, $all->count(), $perPage, $currentPage);
For 4.2
try this syntax:
$items = $all->toArray();
$total = count($items);
$perPage = 10;
$paginator = Paginator::make($items, $total, $perPage);
Upvotes: 0
Reputation: 40909
Laravel 5:
In Laravel 5 it can be easily done by instantiating paginator:
$paginator = new Illuminate\Pagination\Paginator($all, $perPage, $currentPage);
Upvotes: 1