Paginate Laravel Collection

3.4k views Asked by At

I have two different querys that I merge to return a collection

$combinados = $histMe->merge($hist)->sortByDesc('created_at');

And I return them this way:

$final = $combinados->all();

But this prints all the collection, how can I paginate this? The paginate() laravel method doesn't work with collections. And how can I controll it from the view?

Thanks!

3

There are 3 answers

0
Salar Bahador On

You can use this code that I wrote a long time ago:

You must use Length aware paginator:

use Illuminate\Pagination\LengthAwarePaginator;


public function paginate($items, $perPage,$setDefaultOption = true, $options = [])
    {
        if($setDefaultOption){
            $options = ['path' => request()->url(), 'query' => request()->query()];
        }
        $page = Input::get('page', 1); // Get the current page or default to 1


        $items = $items instanceof Collection ? $items : Collection::make($items);

        return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
    }
2
Adam Rodriguez On

The api has changed slightly in newer versions. To paginate a collection you now need to use forPage.

The method forPage takes two parameters:

forPage(int $page, int $perPage)

So you can do something like this in your controller:

...
public function index(Request $request)
{
    $combinados = $histMe->merge($hist)->sortByDesc('created_at');

    $combinados->forPage($request->get('page'), 25);
}
...
1
Mohammed Uvaise c On
 public function paginate($items, $perPage =1,$setDefaultOption = true, $options = [],$page = null)
{
    if($setDefaultOption){
        $options = ['path' => request()->url(), 'query' => request()->query()];
    }
    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);


    $items = $items instanceof Collection ? $items : Collection::make($items);

    return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}



 public function test(){

    $coinUsers = collect([]);
     $users = User::role('Customer')->get();
     foreach ($users as $user) {
        if ($user->balanceFloat > 0) {
            $coinUsers->push($user);
        }
         
    }
     $data = $this->paginate($coinUsers);

    return view('test', array(
        'users' => $data,
    ));
}

Perfectly working on Laravel 8 . Please try like this