Loading image

Blogs / Programming

Laravel 11 Pagination Guide - Complete Tutorial with Examples

Laravel 11 Pagination Guide - Complete Tutorial with Examples

  • showkat ali
  • 0 Comments
  • 87 View

Have you ever tried loading thousands of records simultaneously, only to find your app slowing down to crawl? Pagination is the solution that breaks down enormous datasets into manageable chunks, keeping your app performant and user-friendly. We’ll explore why pagination is essential and dive deep into the pagination options Laravel offers, from traditional offset-based pagination to efficient cursor-based pagination for real-time data.


Why is Pagination Important?

Pagination isn’t just a feature; it’s necessary for modern applications that handle substantial data volumes. Here’s why:

1. Improved Application Performance

  • Database Queries: The database load decreases significantly when smaller data subsets are queryed.
  • Reduced Memory Usage: Only necessary data is loaded, making memory use more efficient.
  • Optimized Network Traffic: With fewer records transferred at a time, data loads faster, benefiting both server and client.

2. Enhanced User Experience

  • Quick Page Loading: Faster load times prevent users from waiting.
  • Intuitive Navigation: Breaking content into pages lets users quickly jump to specific areas.
  • Organized Display: A structured layout makes content less overwhelming.

3. Resource Management

  • Controlled Server Load: Lightens the server’s load, especially during peak times.
  • Database Performance: Faster, predictable query times enhance reliability.
  • Effective Caching: Cache smaller data portions more efficiently per page.

 

Basic Usage

 

Laravel provides three types of pagination:

  1. Simple Pagination (No total count, faster for large datasets)
  2. Full Pagination (Shows total pages & item count)
  3. Cursor Pagination (Best for infinite scroll & large datasets)
  4. Customize Pagination

1. Basic Pagination Example

 

// Controller
use App\Models\Post;

public function index()
{
    $posts = Post::paginate(10); // 10 items per page
    return view('posts.index', ['posts' => $posts]);
}
<!-- Blade View -->
@foreach ($posts as $post)
    <h2>{{ $post->title }}</h2>
    <p>{{ $post->excerpt }}</p>
@endforeach

{{ $posts->links() }} <!-- Renders pagination links -->

 

2. Simple Pagination (Faster for Large Data)

The paginatemethod counts the total number of records matched by the query before retrieving the records from the database. This is done so that the paginator knows how many pages of records there are in total. However, if you do not plan to show the total number of pages in your application's UI, then the record count query is unnecessary.

Therefore, if you only need to display simple "Next" and "Previous" links in your application's UI, you may use the simplePaginate method to perform a single, efficient query:

$posts = Post::simplePaginate(10); // No total count

Best for large datasets where counting all records is slow.

 

3. Cursor Pagination (For Infinite Scroll)

While paginate and simplePaginate create queries using the SQL "offset" clause, cursor pagination works by constructing "where" clauses that compare the values of the ordered columns contained in the query, providing the most efficient database performance available amongst all of Laravel's pagination methods. This method of pagination is particularly well-suited for large data-sets and "infinite" scrolling user interfaces.

Unlike offset based pagination, which includes a page number in the query string of the URLs generated by the paginator, cursor based pagination places a "cursor" string in the query string. The cursor is an encoded string containing the location that the next paginated query should start paginating and the direction that it should paginate:

http://localhost/users?cursor=eyJpZCI6MTUsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0

You may create a cursor based paginator instance via the cursorPaginate method offered by the query builder. This method returns an instance of Illuminate\Pagination\CursorPaginator:

$posts = Post::orderBy('created_at')->cursorPaginate(15);

Ideal for real-time feeds and infinite scroll implementations.

 

Customizing Laravel 11 Pagination

By default, the views rendered to display the pagination links are compatible with the Tailwind CSS framework. However, if you are not using Tailwind, you are free to define your own views to render these links. When calling the links method on a paginator instance, you may pass the view name as the first argument to the method:

{{ $paginator->links('view.name') }}

<!-- Passing additional data to the view... -->
{{ $paginator->links('view.name', ['foo' => 'bar']) }}

However, the easiest way to customize the pagination views is by exporting them to your resources/views/vendor directory using the vendor:publish command:

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

1. Custom Pagination Links

{{ $posts->links('custom.pagination') }} <!-- Uses custom view -->

2. Dynamic Pagination Per Page

// Allow users to select items per page
$perPage = request('per_page', 10);
$posts = Post::paginate($perPage);

Paginator/LengthAwarePaginator Instance Methods

Each paginator instance provides additional pagination information via the following methods:

Method

Description

$paginator->count()

Get the number of items for the current page.

$paginator->currentPage()

Get the current page number.

$paginator->firstItem()

Get the result number of the first item in the results.

$paginator->getOptions()

Get the paginator options.

$paginator->getUrlRange($start, $end)

Create a range of pagination URLs.

$paginator->hasPages()

Determine if there are enough items to split into multiple pages.

$paginator->hasMorePages()

Determine if there are more items in the data store.

$paginator->items()

Get the items for the current page.

$paginator->lastItem()

Get the result number of the last item in the results.

$paginator->lastPage()

Get the page number of the last available page. (Not available when using simplePaginate).

$paginator->nextPageUrl()

Get the URL for the next page.

$paginator->onFirstPage()

Determine if the paginator is on the first page.

$paginator->perPage()

The number of items to be shown per page.

$paginator->previousPageUrl()

Get the URL for the previous page.

$paginator->total()

Determine the total number of matching items in the data store. (Not available when using simplePaginate).

$paginator->url($page)

Get the URL for a given page number.

$paginator->getPageName()

Get the query string variable used to store the page.

$paginator->setPageName($name)

Set the query string variable used to store the page.

$paginator->through($callback)

Transform each item using a callback.

Cursor Paginator Instance Methods

Each cursor paginator instance provides additional pagination information via the following methods:

Method

Description

$paginator->count()

Get the number of items for the current page.

$paginator->cursor()

Get the current cursor instance.

$paginator->getOptions()

Get the paginator options.

$paginator->hasPages()

Determine if there are enough items to split into multiple pages.

$paginator->hasMorePages()

Determine if there are more items in the data store.

$paginator->getCursorName()

Get the query string variable used to store the cursor.

$paginator->items()

Get the items for the current page.

$paginator->nextCursor()

Get the cursor instance for the next set of items.

$paginator->nextPageUrl()

Get the URL for the next page.

$paginator->onFirstPage()

Determine if the paginator is on the first page.

$paginator->onLastPage()

Determine if the paginator is on the last page.

$paginator->perPage()

The number of items to be shown per page.

$paginator->previousCursor()

Get the cursor instance for the previous set of items.

$paginator->previousPageUrl()

Get the URL for the previous page.

$paginator->setCursorName()

Set the query string variable used to store the cursor.

$paginator->url($cursor)

Get the URL for a given cursor instance.

 

 

 

Common Pagination Issues & Fixes

 Problem: Pagination links not working

 Fix: Ensure $items->links() is called in Blade.

 Problem: Duplicate content in Google

 Fix: Use rel="canonical" and rel="prev/next".

 Problem: Slow pagination on large tables

 

 Fix: Use simplePaginate() or cursorPaginate().


Conclusion

 

Laravel 11’s pagination system is powerful and flexible, allowing for efficient data handling while maintaining SEO best practices. By following this guide, you can implement:

 

  • Programming
showkat ali Author

showkat ali

Greetings, I'm a passionate full-stack developer and entrepreneur. I specialize in PHP, Laravel, React.js, Node.js, JavaScript, and Python. I own interviewsolutionshub.com, where I share tech tutorials, tips, and interview questions. I'm a firm believer in hard work and consistency. Welcome to interviewsolutionshub.com, your source for tech insights and career guidance.

0 Comments

Post Comment

Recent Blogs

Recent posts form our Blog

Usefull Laravel Artisan Commands with Examples

Usefull Laravel Artisan Commands with Examples

showkat ali
/
Programming

Read More
The Difference Between === and == in JavaScript: A Complete Guide

The Difference Between === and == in JavaScript: A Complete Guide

showkat ali
/
Programming

Read More
Simplify Image Uploads: Creating a Generic Image Function in Laravel 10

Simplify Image Uploads: Creating a Generic Image Function in Laravel 10

showkat ali
/

Read More
A Step-by-Step Guide: How to Integrate CoinGate with Laravel 10

A Step-by-Step Guide: How to Integrate CoinGate with Laravel 10

showkat ali
/
Programming

Read More
Complete Guide to Spatie Role and Permission in Laravel 11

Complete Guide to Spatie Role and Permission in Laravel 11

showkat ali
/
Programming

Read More
Timeline Chart bar with date axis to be displayed on top

Timeline Chart bar with date axis to be displayed on top

showkat ali
/
Programming

Read More