Sling Academy
Home/PHP/Laravel Eloquent: How to Implement Page Pagination

Laravel Eloquent: How to Implement Page Pagination

Last updated: January 17, 2024

Introduction

Laravel, a powerful and flexible PHP framework, is renowned for its elegance and a rich set of features that boost the productivity of developers. Among these features is Eloquent, Laravel’s own ORM (Object-Relational Mapper), providing an active record implementation for working with your database. In this tutorial, we’ll explore how to implement page pagination with Laravel Eloquent, an essential component for any web application that deals with large datasets.

Prerequisites

First, ensure that you have Laravel installed and configured on your system. If you need help at this stage, refer to one of the following articles:

Basic Pagination

Pagination in Laravel can be implemented quickly and effortlessly using Eloquent. Suppose you have a Post model and you’d like to display 10 posts per page. Here’s a sample method in your controller:

public function index()
{
    $posts = Post::paginate(10);
    return view('posts.index', compact('posts'));
}

In your Blade template file, such as posts/index.blade.php, you can use the links() method provided by Laravel to render pagination links:

<div>
    @foreach ($posts as $post)
        <h2>{{ $post->title }}</h2>
        <p>{{ $post->body }}</p>
    @endforeach
</div>

<div>{{ $posts->links() }}</div>

This code will generate a simple pagination bar. Now, let’s run the application and you will see the pagination links at the bottom of your listed posts.

Customizing Pagination Views

Laravel allows you to customize the pagination view. You can publish the default pagination views using the Artisan command and then modify them according to your website’s design requirements.

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

This will copy the default pagination view files to your resources/views/vendor/pagination directory. From there, you can edit the Blade files to match your design.

Advanced Paginations

Laravel’s Eloquent ORM also supports additional pagination methods like simplePaginate and cursorPaginate. The simplePaginate method is useful if you want to display only ‘Next’ and ‘Previous’ links instead of full pagination controls:

public function index()
{
    $posts = Post::simplePaginate(10);
    return view('posts.index', compact('posts'));
}

To utilize efficient pagination over large datasets, the cursorPaginate method can be used, which makes use of cursor-based pagination:

public function index()
{
    $posts = Post::cursorPaginate(10);
    return view('posts.index', compact('posts'));
}

Both methods can be used in a similar way to the basic paginate method when it comes to rendering the pagination links in your Blade templates.

Filtering and Sorting with Pagination

Often, you need to provide sorting or filtering functionality in conjunction with pagination. Eloquent facilitates this as well. Here’s how to implement filtering with pagination:

use Illuminate\Http\Request;

public function index(Request $request)
{
    $query = Post::query();

    if ($request->has('category')) {
        $query->where('category_id', $request->input('category'));
    }

    $posts = $query->paginate(10);
    return view('posts.index', compact('posts'));
}

If you want to allow users to control the sorting of their results, consider the following controller method:

public function index(Request $request)
{
    $sortBy = $request->input('sort_by', 'created_at');
    $direction = $request->input('direction', 'desc');

    $posts = Post::orderBy($sortBy, $direction)->paginate(10);
    return view('posts.index', compact('posts'));
}

This code snippet enables sorting while maintaining pagination integrity by keeping sort preferences accessible across page requests.

Conclusion

Implementing pagination with Laravel’s Eloquent ORM is a simple yet powerful feature to manage large datasets efficiently. By leveraging Laravel’s built-in pagination methods, developers can provide a better user experience for navigating through data.

Next Article: Laravel Eloquent: How to create ‘infinity scroll’ pagination

Previous Article: Laravel Eloquent: How to Implement Case-Insensitive Search

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array