avatar
paginate collection in laravel Laravel

• First way, you need register macro named `paginate` in AppServiceProvider.php. After that, you can use it as syntax:

collect($array_data)->paginate(5);

Then AppServiceProvider has declaration in `register` function as below:

Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') {
            $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
            return new LengthAwarePaginator(
                $this->forPage($page, $perPage),  
                $total ?: $this->count(),
                $perPage,
                $page,
                [
                    'path' => LengthAwarePaginator::resolveCurrentPath(),
                    'pageName' => $pageName,
                ]
            );
        });

Note: If you observe keys on page 2 and next page. You can use remove it by using:

collect($total)->forPage($page, $perPage)->values(),

replace

$this->forPage($page, $perPage),

• Second way, you can create `PaginationHelper.php` to implement LengthAwarePaginator with the following here:

<?php

namespace App\Helpers;

use Illuminate\Container\Container;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;

class PaginationHelper
{
    public static function paginate(Collection $results, $showPerPage)
    {
        $pageNumber = Paginator::resolveCurrentPage('page');

        $totalPageNumber = $results->count();

//        return self::paginator($results->forPage($pageNumber, $showPerPage), $totalPageNumber, $showPerPage, $pageNumber, [
//            'path' => Paginator::resolveCurrentPath(),
//            'pageName' => 'page',
//        ]);

        return self::paginator(collect($results)->forPage($pageNumber, $showPerPage)->values(), $totalPageNumber, $showPerPage, $pageNumber, [
            'path' => Paginator::resolveCurrentPath(),
            'pageName' => 'page',
        ]);
    }

    /*
     * Create a new length-aware paginator instance.
     *
     * @param Collection $items
     * @param  int  $total
     * @param  int  $perPage
     * @param  int  $currentPage
     * @param  array  $options
     * @return LengthAwarePaginator
     */
    protected static function paginator($items, $total, $perPage, $currentPage, $options)
    {
        return Container::getInstance()->makeWith(LengthAwarePaginator::class, compact(
            'items', 'total', 'perPage', 'currentPage', 'options'
        ));
    }
}

The next, you need to add PaginationHelper.php into `autoload` in `composer.json` file.

"autoload": {
    "files": [
        "app/Helpers/PaginationHelper.php"
    ],
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},

After that, you can call directly from Collection with operator →

PaginationHelper::paginate($array_data, 5);
You need to login to do this manipulation!