Lecture Notes Of Day 15: Pagination in Laravel

 Lecture Notes Of Day 15

Pagination in Laravel

Objective:

  • Learn how to add pagination to web pages in Laravel applications.
  • Understand the concept of pagination and its significance in providing a better user experience when displaying large sets of data.

Introduction to Pagination:

Pagination is a technique used in web development to divide large datasets into smaller, manageable chunks. Instead of displaying a long list of items on a single page, pagination breaks the data into pages, allowing users to navigate between different pages to view the data in smaller parts.

In Laravel, pagination is easy to implement and allows you to display results from your database efficiently.


Key Concepts:

1.  Eloquent Pagination: Laravel's Eloquent ORM provides a built-in method called paginate() to handle pagination for database queries.

2.  Blade Pagination Links: Laravel provides a simple method to generate pagination links in the Blade template system using the links() method.


Step-by-Step Implementation:

1. Setting Up Pagination in Controller

In order to implement pagination in a Laravel controller, we need to follow these steps:

1.  Define the Pagination Query: First, let's assume we have a User model and want to display a paginated list of users. In the controller method, you can use the paginate() function to retrieve data in chunks.

php

Copy code

// UserController.php

public function index()

{

    // Retrieve paginated users (10 users per page)

    $users = User::paginate(10);

   

    // Pass the paginated data to the view

    return view('users.index', compact('users'));

}

o    User::paginate(10) fetches users from the database and limits the result to 10 per page.

o    The result is returned as a LengthAwarePaginator instance, which contains all the necessary data for pagination (e.g., total count, current page, links).

2. Rendering Pagination Links in Blade Template

In the corresponding Blade view file (e.g., users/index.blade.php), you need to render the pagination links:

php

Copy code

<!-- users/index.blade.php -->

 

<h1>User List</h1>

 

<table>

    <thead>

        <tr>

            <th>ID</th>

            <th>Name</th>

            <th>Email</th>

        </tr>

    </thead>

    <tbody>

        @foreach ($users as $user)

            <tr>

                <td>{{ $user->id }}</td>

                <td>{{ $user->name }}</td>

                <td>{{ $user->email }}</td>

            </tr>

        @endforeach

    </tbody>

</table>

 

<!-- Pagination Links -->

<div class="pagination">

    {{ $users->links() }}

</div>

  • {{ $users->links() }}: This directive will automatically generate the pagination links. Laravel will generate HTML for "Previous", "Next", and numbered page links based on the data passed from the controller.

3. Customizing Pagination Links (Optional)

Laravel's default pagination links use Bootstrap classes. However, if you're using a different CSS framework or custom styling, you may want to customize the appearance of the pagination links.

You can customize pagination views by publishing the pagination views and editing them:

bash

Copy code

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

This command will copy the pagination views to your resources/views/vendor/pagination directory. You can edit the HTML structure and classes of the pagination links in that directory.


4. Handling Edge Cases:

  • Empty Results: When there are no results to paginate, Laravel will still render the pagination controls. It's a good idea to check if the result is empty and display a message such as "No records found".

Example:

php

Copy code

@if($users->isEmpty())

    <p>No users found.</p>

@else

    <!-- Pagination Links -->

    {{ $users->links() }}

@endif

  • Customizing Per Page Count: The paginate() method accepts a parameter that specifies how many items to display per page. For example, to display 15 items per page, you can use:

php

Copy code

$users = User::paginate(15);


5. Understanding the Pagination Data

The paginate() method returns a LengthAwarePaginator instance, which has several useful methods:

  • Current Page: $users->currentPage()
  • Total Pages: $users->lastPage()
  • Total Items: $users->total()
  • Items per Page: $users->perPage()

These methods can be useful if you need to display additional information about the pagination, such as showing the current page and total items.

Example:

php

Copy code

<p>Showing {{ $users->firstItem() }} to {{ $users->lastItem() }} of {{ $users->total() }} users.</p>


6. Conclusion

By the end of this lesson, you should now be able to implement basic pagination in a Laravel application. Pagination improves the performance and usability of your application when displaying large sets of data. In Laravel, pagination is simple to implement with just a few lines of code, and you can further customize it to suit your needs.


Practice Exercise:

1.  Create a new model, controller, and view for a Post entity.

2.  Implement pagination to display a list of posts on the page.

3.  Customize the pagination links with a different CSS framework.


Summary:

  • Pagination is used to break down large datasets into manageable chunks.
  • Laravel makes it easy to implement pagination with the paginate() method.
  • You can render pagination links in Blade using {{ $users->links() }}.
  • Customize pagination links if needed and handle cases like empty results.


Comments

Popular posts from this blog

MCQs Of Day CRUD 8 Operations with Eloquent

Lecture Notes Of Day 24: Laravel Policies

MCQs of Day 7 Eloquent ORM Basics