Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Laravel Paginate Collection or Array
<?php
/**
* Gera a paginação dos itens de um array ou collection.
*
* @param array|Collection $items
* @param int $perPage
* @param int $page
* @param array $options
*
* @return LengthAwarePaginator
*/
public function paginate($items, $perPage = 15, $page = null, $options = [])
{
$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);
}
@NicksonYap
Copy link

NicksonYap commented Jan 13, 2019

For those who has issues with second page:

where 2nd page data has keys like:

"data": {
    "5": {
    "userId": "564110eadcb39832268ea873",
    "email": "dsdfgdfg@il.com",
    "isActive": true,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg",
    "permissionType": "dsdfgdfg"
    },
    "6": {
    "userId": "564110ea2169bc358a3b65c2",
    "email": "dsdfgdfg@d.com",
    "isActive": false,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg",
    "permissionType": "dsdfgdfg"
    },
    "7": {
    "userId": "564110eaee662f30c4bd6772",
    "email": "dsdfgdfg@dsdfgdfg.com",
    "isActive": true,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg",
    "permissionType": "dsdfgdfg"
    },
}

This is because forPage() returns an array with keys

Fix is to add array_values():

  public function paginateCollection($items, $perPage = 15, $page = null, $options = [])
    {
        $page = $page ?: (\Illuminate\Pagination\Paginator::resolveCurrentPage() ?: 1);
        $items = $items instanceof \Illuminate\Support\Collection ? $items : \Illuminate\Support\Collection::make($items);
        return new \Illuminate\Pagination\LengthAwarePaginator(array_values($items->forPage($page, $perPage)->toArray()), $items->count(), $perPage, $page, $options);
        //ref for array_values() fix: https://stackoverflow.com/a/38712699/3553367
    }

@biobii
Copy link

biobii commented Feb 4, 2019

Great! This code solves my problem. Thanks!

@mrhaghighi
Copy link

mrhaghighi commented Feb 6, 2019

Thanks!
This code solved my problem.

@Pes8
Copy link

Pes8 commented Feb 14, 2019

Thank you :)

@shashankapporio
Copy link

shashankapporio commented Mar 1, 2019

All who are facing issue on page >= 2, visit at
https://gist.github.com/simonhamp/549e8821946e2c40a617c85d2cf5af5e

Issue:
{ "current_page": 2, "data": { "3": { "ID": 196, "post_author": 3, "post_date": "2017-11-03 08:45:17", "post_date_gmt": "2017-11-03 08:45:17" } } }

@afrazahmmad
Copy link

afrazahmmad commented Jun 17, 2019

To solve second page issue.
chain with values method $items->forPage($page, $perPage)->values()

@twizzlerz04
Copy link

twizzlerz04 commented Jun 26, 2019

Thanks for this :)

@gitipasand
Copy link

gitipasand commented Jun 28, 2019

how to use this solution in ajax

@freelance-github
Copy link

freelance-github commented Jul 26, 2019

I solve it

collect( [ 2 => 'Some value', 5 => 'other value' ] )->paginate(15)

https://gist.github.com/freelance-github/fe8488ff19b1a7ed67223b15c7a25b52

@moin786
Copy link

moin786 commented Dec 17, 2019

@vluzrmos great work man

@thiagolinoz
Copy link

thiagolinoz commented Apr 9, 2020

🤯 wow.
thanks, this helped a lot

@ruffcoins
Copy link

ruffcoins commented May 26, 2020

I'm lost. Please how do i use this?

@tom1slick
Copy link

tom1slick commented Jun 15, 2020

I'm lost. Please how do i use this?

Maybe this example will help you

//Getting current request link
$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

//Using function on the array
$paginated_list = $this->paginate($array_to_paginate, 20, request('page'), ['path' => $actual_link, ]);

@kapitannwel
Copy link

kapitannwel commented Aug 2, 2020

$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => 'page',
]);

this is exactly what i am searching for @PaulAguirre . thank you for your contribution. stay safe!

@Mohamed-Nasr-ALi
Copy link

Mohamed-Nasr-ALi commented Sep 15, 2020

awesome

@ghareebmoh
Copy link

ghareebmoh commented Oct 21, 2020

For those who has issues with second page:

where 2nd page data has keys like:

"data": {
    "5": {
    "userId": "564110eadcb39832268ea873",
    "email": "dsdfgdfg@il.com",
    "isActive": true,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg",
    "permissionType": "dsdfgdfg"
    },
    "6": {
    "userId": "564110ea2169bc358a3b65c2",
    "email": "dsdfgdfg@d.com",
    "isActive": false,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg",
    "permissionType": "dsdfgdfg"
    },
    "7": {
    "userId": "564110eaee662f30c4bd6772",
    "email": "dsdfgdfg@dsdfgdfg.com",
    "isActive": true,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg",
    "permissionType": "dsdfgdfg"
    },
}

This is because forPage() returns an array with keys

Fix is to add array_values():

  public function paginateCollection($items, $perPage = 15, $page = null, $options = [])
    {
        $page = $page ?: (\Illuminate\Pagination\Paginator::resolveCurrentPage() ?: 1);
        $items = $items instanceof \Illuminate\Support\Collection ? $items : \Illuminate\Support\Collection::make($items);
        return new \Illuminate\Pagination\LengthAwarePaginator(array_values($items->forPage($page, $perPage)->toArray()), $items->count(), $perPage, $page, $options);
        //ref for array_values() fix: https://stackoverflow.com/a/38712699/3553367
    }

thank you 👍 👍

@jperalta-EndlessCodeStudio

Thank you very much. Saved my lyfe! 👍 👍

@Kaylakaze
Copy link

Kaylakaze commented Nov 5, 2020

Better yet, just make a macro.

Collection::macro('paginate', function($perPage = 15, $page = null, $options = []) {
            $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
            if (!isset($options['path'])) {
                $options['path'] = '/' . request()->path();
            }
            return new LengthAwarePaginator(array_values($this->forPage($page, $perPage)->toArray()), $this->count(), $perPage, $page, $options);
        });

@kanchanarandika
Copy link

kanchanarandika commented Nov 16, 2020

Thank you very much! This is really helpful

@MarouanAfkir
Copy link

MarouanAfkir commented Dec 29, 2020

For those who has issues with second page:

where 2nd page data has keys like:

"data": {
    "5": {
    "userId": "564110eadcb39832268ea873",
    "email": "dsdfgdfg@il.com",
    "isActive": true,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg",
    "permissionType": "dsdfgdfg"
    },
    "6": {
    "userId": "564110ea2169bc358a3b65c2",
    "email": "dsdfgdfg@d.com",
    "isActive": false,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg",
    "permissionType": "dsdfgdfg"
    },
    "7": {
    "userId": "564110eaee662f30c4bd6772",
    "email": "dsdfgdfg@dsdfgdfg.com",
    "isActive": true,
    "firstName": "dsdfgdfg",
    "lastName": "dsdfgdfg",
    "permissionType": "dsdfgdfg"
    },
}

This is because forPage() returns an array with keys

Fix is to add array_values():

  public function paginateCollection($items, $perPage = 15, $page = null, $options = [])
    {
        $page = $page ?: (\Illuminate\Pagination\Paginator::resolveCurrentPage() ?: 1);
        $items = $items instanceof \Illuminate\Support\Collection ? $items : \Illuminate\Support\Collection::make($items);
        return new \Illuminate\Pagination\LengthAwarePaginator(array_values($items->forPage($page, $perPage)->toArray()), $items->count(), $perPage, $page, $options);
        //ref for array_values() fix: https://stackoverflow.com/a/38712699/3553367
    }

Thanks, mate

@Tuhedul-Islam
Copy link

Tuhedul-Islam commented Jan 31, 2021

/**

  • Gera a paginação dos itens de um array ou collection.
  • @param array|Collection $items
  • @param int $perPage
  • @param int $page
  • @param array $options
  • @return LengthAwarePaginator
    */
    public function paginate($items, $perPage = 2, $page = null)
    {
    $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
    $items = $items instanceof Collection ? $items : Collection::make($items);
    return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, [
    'path' => Paginator::resolveCurrentPath(),
    'pageName' => 'page',
    ]);
    }

Thanks a lot

@mosesegboh
Copy link

mosesegboh commented Mar 7, 2021

please how can it be installed??

@Kaylakaze
Copy link

Kaylakaze commented Mar 8, 2021

Depends on which one you're talking about. For the macro, you put it in your boot() method on AppServiceProvider (or on another service provider if you want). For the general method, you specify a custom collection object for your model and put it on the custom collection.

@cnyambo
Copy link

cnyambo commented Mar 8, 2021

With the same code, I have two pages, one for search where I enter the search criteria and another to display the results. However, when I click to the second or any other page, the system redirect me first to the search page again to reenter the search criteria then bring the result for that specific page. Could you please help to solve this?

@Sarmed-armis
Copy link

Sarmed-armis commented Jul 18, 2021

great for this comments thanks to all

@Gab-Arruda
Copy link

Gab-Arruda commented Aug 30, 2021

Great!! It works just fine. Thanks a lot!!!

@mdbtekny
Copy link

mdbtekny commented Jan 13, 2022

Hello to everyone, how can i use ->links()? Thanks in advance

@vladimir-zarcanin
Copy link

vladimir-zarcanin commented Feb 16, 2022

If you have a problem with pagination add values() method:
return new LengthAwarePaginator($items->forPage($page, $perPage)->values(), $count, $perPage, $page, []);

@Tuhedul-Islam
Copy link

Tuhedul-Islam commented Feb 17, 2022

@vladimir-zarcanin
Copy link

vladimir-zarcanin commented Feb 17, 2022

I have a problems when fetch page > 1, $items->forPage($page, $perPage)->values(). this solved my problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment