Posts Learn Components Snippets Categories Tags Tools new About
/

How to Create Manual Pagination in Laravel Using LengthAwarePaginator

Learn how to create a manual pagination in Laravel using the LengthAwarePaginator class with code examples

Created on Dec 02, 2021

1136 views

To paginate a record or data in Laravel you can easily make use of the paginate method available to the Eloquent Model and Fluent Object.
<?php

$posts = Post::query()->paginate();

$posts = DB::table('posts')->paginate();
Although this solution is very straightforward, there will be at times where you want to paginate something else such as an array or a collection that is not an Eloquent Model and Fluent instance. To achieve that you can create your own Paginator or LengthAwarePaginator to create your own pagination.

Create LengthAwarePaginator in Laravel


To create this pagination you can first import the class from the namespace below.
<?php

use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
Do note that for this example we'll be paginating "Post / Article" data which by default is a collection of arrays. Do bear in mind that in a real-world case this data will an array of something else that you have defined.
<?php

use App\Models\Post
use Illuminate\Pagination\Paginator;
use Illuminate\Pagination\LengthAwarePaginator;

Route::get('posts', function () {
    $posts = Post::get(); // get 1000 posts

    $perPage = 20;
    $currentPage = request("page") ?? 1;

    $pagination = new LengthAwarePaginator(
        $posts->slice($currentPage, $perPage),
        $posts->count(),
        $perPage,
        $currentPage,
        [
            'path' => request()->url(),
            'query' => request()->query(),
        ]
    );

    return view('posts.index', compact('posts'));
});
The LengthAwarePaginator will require 5 parameters which are the items, total of arrays, per page, current page, and also the options if any.
$items, $total, $perPage, $currentPage = null, array $options = []

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)