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:
| First name | Last name | Actions |
|---|---|---|
| {{ $author->first_name }} | {{ $author->last_name }} | Edit |
| No entries found. | ||
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:
Guess what - if we click "Page 2" link or the arrow to the right, it will actually work!
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...