user5149676
user5149676

Reputation: 21

Paginate merged queries

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

Answers (3)

poldixd
poldixd

Reputation: 1202

Laravel 5:

You can use spatie/laravel-collection-macros.

$posts = Post::all();

$comments = Comment:all();

return $comments->merge($posts)->paginate();

Upvotes: 0

The Alpha
The Alpha

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

jedrzej.kurylo
jedrzej.kurylo

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

Related Questions