Pagination

Pagination

Pagination helps managing large datasets by fetching and displaying smaller chunks instead of all at once. Because when you fetch thousands of records at once it can overwhelm your browser. Pagination limits the number of records retrieved and displayed per page, improving performance and user experience.

Implementing Pagination

If you have the “web.php” routes file like this, where you call the “get()” function:

PHP
// Route::get('/jobs', function (){
    $jobs = Job::with('employer')->get();

Replace your query like this:

PHP
$jobs = Job::with('employer')->paginate(3);

This fetches 3 jobs per page along with their employers.

Displaying Pagination Links

In your Blade view, render pagination links with:

PHP
{{ $jobs->links() }}

Laravel automatically generates styled pagination controls, assuming you use Tailwind CSS by default.

Customizing Pagination Views

If you want to customize the pagination markup or use a different CSS framework like Bootstrap, publish the pagination views:

Bash
php artisan vendor:publish --tag=laravel-pagination

This copies the pagination views into your resources/views/vendor/pagination directory for editing.

To switch the default pagination view (e.g., to Bootstrap 5), configure it in AppServiceProvider:

PHP
use Illuminate\Pagination\Paginator;

public function boot()
{
    Paginator::useBootstrapFive();
}

Pagination Types

  • Standard Pagination: Shows page numbers and navigation links.
  • Simple Pagination: Shows only “Previous” and “Next” links, reducing query complexity.
  • Cursor Pagination: Uses a cursor (encoded string) for efficient pagination on large datasets but lacks direct page number navigation.

Example for standard pagination:

PHP
$jobs = Job::with('employer')->paginate(3);

Example for simple pagination:

PHP
$jobs = Job::with('employer')->simplePaginate(3);

Example for simple pagination:

PHP
$jobs = Job::with('employer')->cursorPaginate(3);

How Pagination Queries Work

Standard pagination uses SQL LIMIT and OFFSET to fetch the correct subset of records.

Cursor pagination uses an encoded cursor to fetch records after a certain point, avoiding the performance cost of large offsets.

Tags: