Back to Basics: Laravel Pagination in 2 Minutes

Laravel has a lot of useful functions in the core, one of them is a simple pagination for your table list of entries. Let's see how it works.
Notice: This is a chapter from upcoming mini-course I'm creating now called "How to create admin panel in Laravel", which will be published later this week on QuickAdminPanel.com, but decided to publish some parts as separate short articles. Follow the launch of the full course on Twitter.
Let's say we have a list table of authors, with this code. /app/Http/Controllers/AuthorsController.php:
    public function index()
    {
        $authors = Author::all();
        return view('authors.index', compact('authors'));
    }
And /resources/views/authors/index.blade.php:

        @forelse($authors as $author)
        
        @empty
            
        @endforelse
    
First name Last name Actions
{{ $author->first_name }} {{ $author->last_name }} Edit
{{ csrf_field() }}
No entries found.
Here's the visual result of it all. laravel pagination 01 What if we have more entries and need to have pagination? First, we use paginate() method in Controller instead of all():
    public function index()
    {
        $authors = Author::paginate(5);
        return view('authors.index', compact('authors'));
    }
Next - to display the pagination in our list in the file resources/views/authors/index.php we just use method links() like this:
    
    ...
    
{{ $authors->links() }}
In case of 1-5 entries, it won't display anything, but beyond that we will see something like this: laravel pagination 02 Guess what - if we click "Page 2" link or the arrow to the right, it will actually work! laravel pagination 03 As you can see, paginator will add a GET parameter to the URL ?page=2, and we don't need to add any custom code to make it work. Isn't that awesome? Of course, you can perform a lot of customizations with this pagination - move the page length to config, change URL parameters and add your own ones, apply different styling than default etc. But I will leave it for you to play around, if you wish. More information about pagination in Laravel can be found in the official documentation.

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 58 courses (1054 lessons, total 46 h 42 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials