Home / Snippets / How to Create Manual Pagination in Laravel Using LengthAwarePaginator
How to Create Manual Pagination in Laravel Using LengthAwarePaginator cover

How to Create Manual Pagination in Laravel Using LengthAwarePaginator

4.7K

3 years ago

0 comments

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 = []
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this