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);
}
@amandalima

This comment has been minimized.

Copy link

commented Aug 11, 2016

Great!

@LarryEitel

This comment has been minimized.

Copy link

commented Jun 30, 2017

Sweet!! :)

I just crammed that function inside a controller (for now) and ran:

        $collection = $qry->get();
        return $this->paginate($collection, $perPage = 15, $page = null, $options = []);
@Arslan1122

This comment has been minimized.

Copy link

commented Sep 19, 2017

how to display it on view in laravel ?

@ahmadarif

This comment has been minimized.

Copy link

commented Sep 23, 2017

Error format at page 2

{
    "current_page": 2,
    "data": {
        "3": {
            "month": 6,
            "year": 2017,
            "url": "http://127.0.0.1:8000/api/eph/download/eyJpdiI6ImZIdEJHdHlsZjlMd2tpUlV5c1BHUVE9PSIsInZhbHVlIjoieHRMOGpPNWltRVNQTFZDMWliQkQ0dz09IiwibWFjIjoiMzAwM2Q0ZWM0OGY5ODMwYWFmMzAzZWU5OTYzYzg0OWQxNzI5YjNhNjAxYTdlNGQ3ZmQ2NTIyYzdmNDY1NmNlNSJ9"
        },
        "4": {
            "month": 6,
            "year": 2017,
            "url": "http://127.0.0.1:8000/api/eph/download/eyJpdiI6IkU1RE5MbVJFbVkyc2NDb1RJRDlCTUE9PSIsInZhbHVlIjoiRFJYcnBETlhheW1xOVwvQ2dwSE8zSlE9PSIsIm1hYyI6IjRkOTNjOWFkNzIyYzFkYjJjNjg4ZDM1MGFkMDdkMmQzZjkzMzc1YjJjYzVjMDI0MzFmYTM1MWMzN2RlZjg3MTUifQ=="
        }
    }
}
@scrapewww

This comment has been minimized.

Copy link

commented Oct 5, 2017

I need this for simplePaginate

@wuiler

This comment has been minimized.

Copy link

commented Nov 20, 2017

I had an issue with this pagination, the first page return and jsonObject or passing http://url?page=1:

   "current_page": 1,
   "data": [
       {
           "code": "0001",
           "text": "TEXT1"
        }, .....

but the second page and all the rest of page not return the same object:

   "current_page": 1,
   "data": {
       "20": { <------ THAT the difference
           "code": "0001",
           "text": "TEXT1"  
             }, .....

Like laravel docs said the collection es slide in method ->forPage(), but?
Any one can solved that?

@dreenot

This comment has been minimized.

Copy link

commented Nov 24, 2017

If someone had problem in internal pages see my fork

@jechav

This comment has been minimized.

Copy link

commented Nov 30, 2017

the solution is here

@wuiler

This comment has been minimized.

@jesseyofferenvan

This comment has been minimized.

Copy link

commented Feb 21, 2018

This works likes a charm, even on laravel 5.5 cheers!

@dsmarion

This comment has been minimized.

Copy link

commented Mar 29, 2018

brilliant solution - works great for me!

@PaulaAguirre

This comment has been minimized.

Copy link

commented May 8, 2018

/**
* 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',
]);
}

@ctf0

This comment has been minimized.

@sineld

This comment has been minimized.

Copy link

commented Jun 20, 2018

You may convert it to a helper function:

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($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}

Usage:

{!! paginateCollection($collection, 2) !!}

@ahkmunna

This comment has been minimized.

Copy link

commented Aug 6, 2018

Instead of proper navigators, I'm getting something like this.

[first_page_url] => /?page=1
[from] => 1
[last_page] => 2
[last_page_url] => /?page=2
[next_page_url] => /?page=2
[per_page] => 6
[prev_page_url] => 
[to] => 6
[total] => 12
@azazqadir

This comment has been minimized.

Copy link

commented Oct 23, 2018

Great share. Using array in simple Laravel paginate method is best way to implement pagination in a website. This makes pagination in Laravel even better. If you intend to use front-end, you can also use vue for implementing pagination as well.

@Quix0r

This comment has been minimized.

Copy link

commented Oct 30, 2018

Maybe use $collection for avoiding assigning a parameter? Just a small thought. :-)

@shellprog

This comment has been minimized.

Copy link

commented Nov 4, 2018

If the links are not correct, pass the current page path in options like below
$this->paginate($posts, 10, request('page'), ['path' => request()->path()]);

@Concaking

This comment has been minimized.

Copy link

commented Nov 11, 2018

Thanks @PaulaAguirre. Greate solution work best for my app

@JunaidQadirB

This comment has been minimized.

Copy link

commented Jan 4, 2019

This will allow you to pass the baseUrl for the LengthAwarePaginator


    public function paginate($items, $perPage = 15, $page = null, $baseUrl = null, $options = [])
    {
        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);

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

        $lap = new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);

        if ($baseUrl) {
            $lap->setPath($baseUrl);
        }

        return $lap;
    }
@NicksonYap

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented Feb 4, 2019

Great! This code solves my problem. Thanks!

@mrhaghighi

This comment has been minimized.

Copy link

commented Feb 6, 2019

Thanks!
This code solved my problem.

@Pes8

This comment has been minimized.

Copy link

commented Feb 14, 2019

Thank you :)

@shashankapporio

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented Jun 17, 2019

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

@twizzlerz04

This comment has been minimized.

Copy link

commented Jun 26, 2019

Thanks for this :)

@gitipasand

This comment has been minimized.

Copy link

commented Jun 28, 2019

how to use this solution in ajax

@freelance-github

This comment has been minimized.

Copy link

commented Jul 26, 2019

I solve it

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.