How to Implement Pagination in Laravel 10 Using Bootstrap

laravel simple pagintion example with Laravel 9

Pagination is a crucial technique for handling large datasets in web applications. By breaking down massive amounts of data into smaller, more manageable pages, pagination can improve performance and user experience. Laravel 10 simplifies the implementation of pagination, allowing developers to easily create paginated views.

In this blog, we’ll cover the essentials of implementing pagination in Laravel 10. We’ll begin with the prerequisites for setting up simple pagination using Bootstrap. After that, we’ll dive into the advanced practices followed by Laravel development experts for custom pagination controls and filtering. With that said, let’s get started!

What is Laravel Pagination?

Pagination is the process of dividing large datasets into smaller, manageable chunks or pages, making it easier for users to navigate through the data. Instead of showing all information on one page, pagination offers a better user experience by displaying only a specific amount of data at a time. This feature is especially useful when dealing with large datasets, helping improve performance and usability.

In Laravel, implementing pagination is straightforward. By default, Laravel offers two pagination view options: pagination::slider and pagination::simple. The slider view shows a range of context based on the current page, while simple pagination only includes previous and next buttons. Both options work seamlessly with Twitter Bootstrap, making pagination easy to integrate and customize in your Laravel application.

Prerequisites for Laravel 10 Simple Pagination Using Bootstrap

Before you start implementing pagination in Laravel 10 with Bootstrap, make sure you have the following prerequisites:Laravel 10 Installation: Ensure that you have Laravel 10 installed and running on your local development environment. You can install Laravel using Composer by running the following command:

composer create-project --prefer-dist laravel/laravel your-project-name

Basic Knowledge of Laravel Components: Familiarity with Eloquent ORM, Blade templates, and routing in Laravel is essential. Understanding how to query data using Eloquent models and pass it to Blade views will help you implement pagination smoothly.

A Working Database: You should have a working database set up with at least one table, such as the posts table, for the purpose of pagination. You can create a basic table by running migrations:

php artisan make:migration create_posts_table

Bootstrap Integration: Laravel 10 doesn’t come with Bootstrap by default, so you need to add it to your project for styling the pagination links. You can include Bootstrap by adding its CDN in the resources/views/layouts/app.blade.php file within the <head> section:

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">

Once these prerequisites are in place, you’ll be ready to dive into the tutorial and start implementing simple pagination with Bootstrap in Laravel 10.

Need Help Implementing Laravel Pagination? We Can Help!

Examples of Simple Pagination in Laravel 10

In this section, we’ll walk through a simple implementation of pagination in Laravel 10 using the Eloquent ORM. You’ll learn how to paginate data, display pagination links, and customize them to fit your design needs using Bootstrap.

Basic Pagination with Eloquent ORM

Let’s assume you have a Post model with the following schema:

// database/migrations/xxxx_xx_xx_create_posts_table.php
public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->text('content');
        $table->timestamps();
    });
}

Now, let’s populate the posts table with some data and implement basic pagination.

Example: Fetching Paginated Results

In your Laravel controller, you can use the paginate() method provided by Eloquent to fetch paginated results. For instance:

use App\Models\Post;

public function index()
{
    // Fetch 10 posts per page
    $posts = Post::paginate(10);

    return view('posts.index', compact('posts'));
}

In the above code, Post::paginate(10) will retrieve 10 posts per page. It automatically handles the offset and limit for you based on the current page, making it much easier to manage large datasets.

Displaying Pagination Links in Blade

To display pagination links in your Blade view, use the links() method. Here is the code you can use:

// resources/views/posts/index.blade.php
@foreach ($posts as $post)
    <div class="post">
        <h3>{{ $post->title }}</h3>
        <p>{{ $post->content }}</p>
    </div>
@endforeach
<!-- Pagination Links -->
{{ $posts->links() }}

By default, Laravel provides simple pagination controls using the simple-bootstrap-4 pagination view (if you’re using Bootstrap 4). If you’re using a different front-end framework, you can customize the pagination view.

Customizing the Pagination Links

You can customize the pagination view to match your design needs. For instance, to use Bootstrap 5 pagination links, you can pass the specific pagination view to the links() method:

{{ $posts->links('pagination::bootstrap-5') }}

Laravel ships with several predefined pagination views, but you can also create your own by publishing the pagination views:

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

After running this command, you can modify the pagination view located in resources/views/vendor/pagination, allowing you to fully customize how the pagination links are displayed in your app.

With Laravel’s built-in pagination tools, managing large datasets becomes easier, providing users with a seamless browsing experience. Customize it to suit your application’s needs and improve data navigation. If you are looking to scale your website while enhancing user-experience, consider getting in touch with our Laravel development company.

Advanced Pagination Practices in Laravel 10

Advanced pagination techniques in Laravel 10 allow you to manage large datasets efficiently while offering users a seamless experience. Here, we’ll cover how to apply filters, retain query parameters, customize queries, and more to enhance your application’s pagination functionality.

Pagination with Filters

Often, you will need to paginate filtered data, such as when the user applies search filters. Here’s how you can combine pagination with filters.

Example: Filtering Posts by Title

Suppose you want to paginate posts based on a search query entered by the user. You can modify your controller like this:

public function index(Request $request)
{
    $query = Post::query();
    if ($request->has('search') && $request->search != '') {
        $query->where('title', 'like', '%' . $request->search . '%');
    }
    $posts = $query->paginate(10);
    return view('posts.index', compact('posts'));
}

Explanation: First, we create a base query with Post::query(). If the user submits a search query parameter, we filter the posts by the title using the like operator. Finally, we paginate the results using paginate(10).

Keeping Query Parameters in Pagination Links

When applying filters, you often need to retain the filter query parameters in the pagination links. Laravel makes this easy with the appends() method.

Example: Retaining Filter Parameters in Pagination Links

public function index(Request $request)
{
    $query = Post::query();
    if ($request->has('search') && $request->search != '') {
        $query->where('title', 'like', '%' . $request->search . '%');
    }
    $posts = $query->paginate(10)->appends(['search' => $request->search]);
    return view('posts.index', compact('posts'));
}

Explanation: We append the search query parameter to the pagination links using appends(), ensuring that the filters persist across pages.

Customizing the Pagination Query

Laravel allows you to customize the pagination query by adding conditions to the Paginator or LengthAwarePaginator class.

Example: Dynamically Changing the Number of Items Per Page

public function index(Request $request)
{
    $perPage = $request->has('per_page') ? (int)$request->get('per_page') : 10;
    $posts = Post::paginate($perPage);
    return view('posts.index', compact('posts'));
}

Explanation: The number of posts per page is determined by the per_page query parameter (or defaults to 10).

Using the Query Builder for Pagination

In some cases, you might prefer using the query builder instead of Eloquent. Here’s how you can paginate results with Laravel’s query builder.

Example: Pagination with Query Builder

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

Explanation: The usage is identical to Eloquent pagination, but instead of using the Post model, you’re directly interacting with the posts table through the DB facade.

Adding Sorting to Pagination

A common pattern when displaying paginated data is to allow users to sort the data based on a column (e.g., by date, title, or popularity).

Example: Sorting Paginated Data

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

    $posts = Post::orderBy($sortBy, $order)->paginate(10);

    return view('posts.index', compact('posts'));
}

Explanation: Users can pass sort_by and order parameters in the query string to sort the posts. For example using the logic /posts?sort_by=title&order=asc will sort posts alphabetically in ascending order.

Paginating Relationships

Sometimes, you need to paginate related models. Let’s say each Post has many comments, and you want to paginate the comments for each post.

Example: Paginating Comments of a Post

public function show(Post $post)
{
    $comments = $post->comments()->paginate(5);
    return view('posts.show', compact('post', 'comments'));
}

Explanation: We paginate the comments related to the post and pass them to the view, making it easy to handle large amounts of related data in a paginated format.

By utilizing these advanced pagination practices, you can build more user-friendly pagination systems that improve both performance and the user experience.

Want expert assistance with your Laravel project?

FAQs About Laravel 10 Pagination Example

What is the alternative to paginate in Laravel?
An alternative to paginate() in Laravel is using simplePaginate(). This method only provides "previous" and "next" links, which is more efficient when you don’t need to display the total number of pages, reducing the overhead of calculating total results.
How to create custom pagination in Laravel 10?
To create custom pagination in Laravel 10, you can publish the pagination views using php artisan vendor:publish --tag=laravel-pagination. After that, you can modify the pagination view files in resources/views/vendor/pagination to match your design needs.
What is the difference between simple pagination and pagination in Laravel?
The main difference is that simplePaginate() only shows "previous" and "next" buttons without displaying the total number of pages, making it faster for large datasets. In contrast, paginate() shows all pagination links, including page numbers, offering more navigation options but requiring more resources.

Wrapping Up

Pagination is required in Laravel websites when handling large datasets, as it helps in dividing content into smaller chunks across multiple pages. That improves the user experience by loading only a specific number of items per page, reducing load times.

In dynamic websites, pagination is key for creating user-friendly interfaces that allow navigation through content, in blogs and eCommerce sites, and more. Using pagination not only enhances performance but also allows you to build scalable Laravel websites.

If you are looking to create a robust, scalable and secure website that performs optimally, hire Laravel developers.

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment