Home > Backend Development > PHP Tutorial > Fine-tuning Pagination Links in Laravel

Fine-tuning Pagination Links in Laravel

Johnathan Smith
Release: 2025-03-07 00:02:10
Original
629 people have browsed it

Fine-tuning Pagination Links in Laravel

Laravel's onEachSide method offers granular control over the pagination links displayed near the current page, enhancing navigation clarity. Instead of relying on the default link count, you can tailor the display to suit your application's specific needs.

This is especially beneficial for applications handling datasets of varying sizes. For larger datasets, you might want to show more navigation options; for smaller ones, a cleaner, less cluttered interface is preferable.

Here's how to implement adaptive pagination:

<?php namespace AppHttpControllers;

use AppModelsArticle;
use IlluminateHttpRequest;

class ArticleController extends Controller
{
    public function index(Request $request)
    {
        $perPage = $this->determinePerPage($request);
        $articles = Article::latest()
            ->withCount('comments')
            ->paginate($perPage);
        $linksToShow = $this->calculateVisibleLinks($articles);

        return view('articles.index', compact('articles', 'linksToShow'));
    }

    private function determinePerPage(Request $request): int
    {
        return $request->query('show', 10);
    }

    private function calculateVisibleLinks($paginator): int
    {
        $totalPages = $paginator->lastPage();

        // Dynamically adjust visible links based on total pages
        return match(true) {
            $totalPages > 20 => 3,
            $totalPages > 10 => 2,
            default => 1
        };
    }
}
Copy after login

In your blade template (articles.index.blade.php):

{{ $articles->onEachSide($linksToShow)->links() }}
Copy after login

This results in a dynamic pagination display:

<code>// ~50 articles (5 pages)
« 1 2 3 4 5 »

// ~150 articles (15 pages)
« 1 ... 4 5 6 7 8 ... 15 »

// ~250 articles (25 pages)
« 1 ... 4 5 6 7 8 9 10 ... 25 »</code>
Copy after login

The onEachSide method, combined with dynamic link calculation, creates a more user-friendly and adaptable pagination experience.

The above is the detailed content of Fine-tuning Pagination Links in Laravel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template