Laravel - Pagination Customizations

Hello, aspiring developers! Today, we're going to dive into the wonderful world of Laravel pagination customizations. As your friendly neighborhood computer science teacher, I'm excited to guide you through this journey. Don't worry if you're new to programming – we'll start from the basics and work our way up. So, grab a cup of coffee (or tea, if that's your thing), and let's get started!

Laravel - Pagination Customizations

What is Pagination?

Before we jump into customizations, let's understand what pagination is. Imagine you have a book with hundreds of pages. Reading all of them at once would be overwhelming, right? That's where pagination comes in. In web development, pagination is like dividing your book into manageable chunks, showing a limited number of items per page.

Laravel, our superhero framework, comes with built-in pagination features that make our lives easier. But sometimes, we want to add our own flair to these paginated results. That's where customizations come in handy!

Basic Pagination in Laravel

Let's start with a simple example of how pagination works in Laravel:

$users = User::paginate(15);

This line of code fetches users from the database and paginates them, showing 15 users per page. It's like magic, isn't it? But what if we want to make this pagination look fancier? That's where our customization journey begins!

Customizing the Pagination View

Step 1: Publishing the Pagination Views

First, we need to publish Laravel's pagination views. Don't worry; it's simpler than it sounds! Run this command in your terminal:

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

This command is like telling Laravel, "Hey, I want to see those pagination files so I can tweak them!"

Step 2: Modifying the View

Now, navigate to resources/views/vendor/pagination. You'll find several files here. Let's focus on default.blade.php. This file controls how your pagination links look.

Here's a simple customization:

@if ($paginator->hasPages())
    <nav>
        <ul class="pagination">
            {{-- Previous Page Link --}}
            @if ($paginator->onFirstPage())
                <li class="disabled"><span>&laquo;</span></li>
            @else
                <li><a href="{{ $paginator->previousPageUrl() }}" rel="prev">&laquo;</a></li>
            @endif

            {{-- Pagination Elements --}}
            @foreach ($elements as $element)
                {{-- "Three Dots" Separator --}}
                @if (is_string($element))
                    <li class="disabled"><span>{{ $element }}</span></li>
                @endif

                {{-- Array Of Links --}}
                @if (is_array($element))
                    @foreach ($element as $page => $url)
                        @if ($page == $paginator->currentPage())
                            <li class="active"><span>{{ $page }}</span></li>
                        @else
                            <li><a href="{{ $url }}">{{ $page }}</a></li>
                        @endif
                    @endforeach
                @endif
            @endforeach

            {{-- Next Page Link --}}
            @if ($paginator->hasMorePages())
                <li><a href="{{ $paginator->nextPageUrl() }}" rel="next">&raquo;</a></li>
            @else
                <li class="disabled"><span>&raquo;</span></li>
            @endif
        </ul>
    </nav>
@endif

This code might look intimidating at first, but let's break it down:

  1. We check if there are multiple pages ($paginator->hasPages()).
  2. We create a navigation with an unordered list.
  3. We add a "Previous" link if we're not on the first page.
  4. We loop through the pagination elements, adding links for each page.
  5. We add a "Next" link if there are more pages.

Styling Your Pagination

Now that we've customized our pagination structure, let's make it look pretty! Add some CSS to your stylesheet:

.pagination {
    display: flex;
    list-style: none;
    padding: 0;
}

.pagination li {
    margin: 0 5px;
}

.pagination li a {
    text-decoration: none;
    padding: 5px 10px;
    border: 1px solid #ddd;
    color: #333;
}

.pagination li.active span {
    background-color: #007bff;
    color: white;
    padding: 5px 10px;
    border: 1px solid #007bff;
}

.pagination li.disabled span {
    color: #ccc;
    padding: 5px 10px;
    border: 1px solid #ddd;
}

This CSS will give your pagination a clean, modern look. It's like putting a nice suit on your code!

Advanced Customizations

Custom Pagination Using Presenter

For more advanced customizations, Laravel allows us to create a custom presenter. Let's create one:

  1. Create a new file app/Http/Presenters/CustomPaginationPresenter.php:
<?php

namespace App\Http\Presenters;

use Illuminate\Pagination\BootstrapPresenter;

class CustomPaginationPresenter extends BootstrapPresenter
{
    public function render()
    {
        if (!$this->hasPages()) {
            return '';
        }

        return sprintf(
            '<div class="custom-pagination">%s %s %s</div>',
            $this->getPreviousButton(),
            $this->getLinks(),
            $this->getNextButton()
        );
    }

    protected function getAvailablePageWrapper($url, $page, $rel = null)
    {
        $rel = is_null($rel) ? '' : ' rel="' . $rel . '"';

        return '<span class="page-item"><a class="page-link" href="' . $url . '"' . $rel . '>' . $page . '</a></span>';
    }

    protected function getDisabledTextWrapper($text)
    {
        return '<span class="page-item disabled"><span class="page-link">' . $text . '</span></span>';
    }

    protected function getActivePageWrapper($text)
    {
        return '<span class="page-item active"><span class="page-link">' . $text . '</span></span>';
    }
}
  1. Use this custom presenter in your controller:
use App\Http\Presenters\CustomPaginationPresenter;

public function index()
{
    $users = User::paginate(15);
    $presenter = new CustomPaginationPresenter($users);

    return view('users.index', compact('users', 'presenter'));
}
  1. In your view, use the custom presenter:
{!! $presenter->render() !!}

Conclusion

Congratulations! You've just learned how to customize Laravel's pagination. From basic modifications to advanced presenters, you now have the power to make your paginated results look exactly how you want them to.

Remember, the key to mastering these concepts is practice. Try creating different styles, experiment with the presenter, and most importantly, have fun with it! Pagination might seem like a small detail, but it can greatly enhance the user experience of your application.

As we wrap up, here's a table summarizing the methods we've covered:

Method Description
paginate() Basic pagination method
vendor:publish Publishes pagination views
hasPages() Checks if there are multiple pages
onFirstPage() Checks if on the first page
previousPageUrl() Gets URL for the previous page
nextPageUrl() Gets URL for the next page
currentPage() Gets the current page number
hasMorePages() Checks if there are more pages

Keep coding, keep learning, and remember – every great developer started as a beginner. You're on your way to becoming a Laravel pagination pro!

Credits: Image by storyset