Today we are going to add a pagination to our list of posts. We will explain how to add different types of pagination. The first type will be a simple pagination (next and previous), the second one with numbers and the last one will be a custom pagination.
Simple pagination
First let’s see how to add a simple pagination. In this type of pagination, we will simply get a two buttons where we can choose to go to the previous page or the next page.
Open the controller and replace the line that makes the query in the index method by this:
1 2 3 |
... $posts = Post::orderBy('id', 'desc')->simplePaginate(6); .. |
What it does is to take all the posts, order them by desc. id and paginate the results every 6 posts. That is, in each page will appear a maximum of 6 posts.
Once this is done, we must add in the view (outside the loop) these lines to show the pagination:
1 2 3 |
@if (count($posts)) {{ $posts->links() }} @endif |
Pagination with numbers
This type of pagination will display the pages by numbers.
Open the controller and modify the same line as before:
1 2 3 |
... $posts = Post::orderBy('id', 'desc')->paginate(6); .. |
This line does the same as the previous one, but a different page will be displayed.
The view’s code is the same as the simple pagination.
Custom pagination
This type is a bit more laborious to apply, it will be a personalized pagination, since we can give the style that we want easily by modifying the HTML a bit.
First of all, I have to say that we are going to follow a StackOverflow post.
Create a file in resources/views/includes called pagination.blade.php and it will have the content of StackOverflow’s post:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@if ($paginator->lastPage() > 1) <ul class="custom-pagination"> <li class="{{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}"> <a href="{{ $paginator->url(1) }}">Previous</a> </li> @for ($i = 1; $i <= $paginator->lastPage(); $i++) <li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}"> <a href="{{ $paginator->url($i) }}">{{ $i }}</a> </li> @endfor <li class="{{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}"> <a href="{{ $paginator->url($paginator->currentPage()+1) }}" >Next</a> </li> </ul> @endif |
I have modified the class attribute from pagination to custom-pagination, because otherwise, it would look just like the pagination with numbers and you could not see the difference.
In the view, we will replace the line previously put by this one:
1 |
@include('includes.pagination', ['paginator' => $posts]) |
Note: so that Laravel can access certain methods that are called in the custom pagination include, we must use, in the controller, the paginate method.
And with this we can modify the HTML and add the design we want through CSS.
-
-Pagination: https://laravel.com/docs/5.4/pagination
-Custom pagination: https://stackoverflow.com/a/30298599