Paginate a array in laravel

    By: Thad Mertz
    2 years ago

    Hi guys In this article we are going to create custom pagination from array in laravel. Any laravel version is fine.

    So lets get started


    First we need a function. So in any controller where you want to add custom pagination add this function.


    Creating Paginate Class


    public function paginate($items, $perPage = 4, $page = null)
    {
        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
        $total = count($items);
        $currentpage = $page;
        $offset = ($currentpage * $perPage) - $perPage ;
        $itemstoshow = array_slice($items , $offset , $perPage);
        return new LengthAwarePaginator($itemstoshow ,$total ,$perPage);
    }
    

    OK in above code we have a function called "paginate". Here mainly we are passing 4 as posts per page. $items can be your array variable. then we have $page.

    So if you want to set second page as first page in pagination you can pass $page. By default we have it as null not compulsory to pass value for it.

    Rest all is pretty straight forwards as we have

    • $total -> as total number of posts.
    • $current page -> as name suggests the value for current page.
    • $offset -> This is required to get different posts on each page.

    Mainly we are using "LengthAwarePaginator" class which is doing the heavy lifting for us.

    So make sure you include these below given lines in the same file where you use this function.


    Include Required Files


    use Illuminate\Pagination\Paginator;
    use Illuminate\Pagination\LengthAwarePaginator;
    

    OK Lets see how things work here

    Here is how you do using laravel pagination.

    Which outputs something like this


    Now lets see if we get a array and the we have to do

    So here is our data as array


    Here we have pagination method present in same controller so calling it using "$this".

    Here how output looks


    Check results


    Lets see what code we added in blade file

    Mainly the same code as you need for laravel pagination.


    Check our video guide for more clarity.