PHP

Efficiently Paginate Eloquent Query Results

Implement pagination for your Eloquent models to present large datasets in manageable chunks, improving performance, loading times, and user experience.

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class PostController extends Controller
{
    public function index()
    {
        // 1. Basic pagination: Retrieves 15 posts per page.
        // Returns an Illuminate\Pagination\LengthAwarePaginator instance.
        $posts = Post::orderBy('created_at', 'desc')->paginate(15);

        // 2. Simple pagination: Ideal for large datasets or when total count isn't needed.
        // Only shows 'next' and 'previous' links, more efficient as it doesn't run COUNT(*).
        // Returns an Illuminate\Pagination\Paginator instance.
        $simplePosts = Post::orderBy('title', 'asc')->simplePaginate(10);

        // 3. Customizing the page name in the URL query string (default is 'page')
        $customPagePosts = Post::paginate(5, ['*'], 'articlesPage'); // e.g., ?articlesPage=2

        // 4. Manual pagination (if you have an array/collection not from a query builder)
        // use Illuminate\Pagination\Paginator;
        // use Illuminate\Support\Collection;
        // $items = Collection::make([/* ... your data array ... */]);
        // $perPage = 10;
        // $page = Paginator::resolveCurrentPage('manualPage');
        // $currentPageSearchResults = $items->slice(($page - 1) * $perPage, $perPage)->all();
        // $manualPaginator = new Paginator($currentPageSearchResults, $perPage, $page, ['path' => Paginator::resolveCurrentPath()]);

        return view('posts.index', [
            'posts' => $posts,
            'simplePosts' => $simplePosts,
            'customPagePosts' => $customPagePosts,
            // 'manualPaginator' => $manualPaginator,
        ]);
    }

    // In your Blade view (e.g., posts/index.blade.php):
    // <div class="container">
    //     @foreach ($posts as $post)
    //         <h3>{{ $post->title }}</h3>
    //         <p>{{ Str::limit($post->body, 100) }}</p>
    //     @endforeach
    //
    //     {{ $posts->links() }}
    //
    //     <hr>
    //
    //     <h2>Simple Pagination Example</h2>
    //     @foreach ($simplePosts as $post)
    //         <p>{{ $post->title }}</p>
    //     @endforeach
    //     {{ $simplePosts->links() }}
    //
    //     <hr>
    //
    //     <h2>Custom Page Name Example</h2>
    //     @foreach ($customPagePosts as $post)
    //         <p>{{ $post->title }}</p>
    //     @endforeach
    //     {{ $customPagePosts->links() }}
    // </div>
}
How it works: Laravel's pagination features are essential for handling large datasets without performance degradation. The `paginate()` method automatically handles calculating the total number of results and offsetting queries, returning a `LengthAwarePaginator` instance suitable for displaying '1 of X' type links. For even greater efficiency on very large tables where the total count isn't strictly necessary, `simplePaginate()` returns a `Paginator` with just 'next' and 'previous' links. Both methods are easily rendered in Blade views using the `links()` helper.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs