How to use Pagination in Laravel?
Hello everyone!
We will discuss pagination in Laravel! It sound’s good, right ? It’s really useful and the easiest way to paginate your web app’s content!
To be honest, I really like to use paginate option in Laravel. Normally, you have to develop a few functions to paginate your data that comes from your database but Laravel already thinks it for you! I mean, no worries. Everything is ready to use fastly.
Let’s talk about paginate first.
You visit a lot of websites or similar apps in a day. For example, e-commerce websites show products to us but they have a lot of products in their database and they can’t show it all at the same time. If they try we will have page load and speed trouble etc. No one likes that the website works slowly. It’s a non-user-friendly option to keep users on the website. We don’t see as a user but a lot of requests going to backend and database when we want to show products on any website. So, they need a solution to showing them step by step or they need a better way to protect page load speed. Pagination is one of the solutions to make web apps faster, useful, and user-friendly.
The E-commerce app has 100 products in a category and the app shows them in tens and the app expects action (like click NEXT option, scrolling the page, etc.) from the user to load the next ten products to the page. Paginate organize your database management in this way and make your response as groups. (100 / 10) -> (fist 10 product, second 10 product …)
Let’s see how Laravel use paginates option!
Laravel Pagination Usage
As you can see in our example, we requested for the products with its relation and paginated products as 10 per page. I mean, when we show them in view we will see only 10 products.
In our example, we return products to view.
How you will show paginate selections in view ?
If you want to have selections for paginated products, Laravel let us get the below view to use it easily.
$products->links()
You can reach links as below but to reach it you need to use specific syntax like :
{!! $products->links() !!}
If you use it like this, you will see paginate options when you display the page.
On the other hand, links() has different types to display clickable options.
paginate()
simplePaginate()
cursorPaginate()
…
I will share detailed links in the resource section. You can use them as your needs in your project. I have used very basic and easy examples to show how we use it in Laravel Apps but you can use it as your application’s structure. Paginate really makes your app more useful and simple for users. You don’t need too many lines to get grouped data from your database. There are lots of usage types in different projects. It helps developers building their apps faster. Isn’t it?
Share your thoughts with me about the paginating option.
Enjoy Your Coding!
Resources :
Enver ŞANLI
Developer, Social Thinker & Farmer