Laravel 5.4 #10 : Pagination

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:

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:

 

Pagination with numbers

This type of pagination will display the pages by numbers.

Open the controller and modify the same line as before:

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:

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:

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