How to Paginate Query for Laravel API (RestFul)?

Enver Şanlı
2 min readJan 9, 2022
Laravel API Pagination
Laravel API Pagination

We discussed Laravel Pagination before, if you didn’t see that you can follow this link to reach our previously published content.

Laravel lets you develop advanced API projects and the project has many rows to respond but you need to think also for your app’s performance. Pagination will help you to increase the app’s performance for responses.

In the other frameworks, paginating your rows can be difficult but Laravel makes it easy and useful. You can use it very easily with your query builder. We discussed paginate for view response and we will discuss another way to your API project.

Let’s make it easy.

Describe a Paginate Class

Firstly, I used a class to get pagination variables from a Request. My class is named as PaginateData and this class will respond to paginate variables directly and we can use that easily. If the request doesn’t have to paginate variables, then we can use default values.

Why I used the PaginateData, I wanted to make it regular and standard because I wanted to use it everywhere in my project whenever I want.

Paginate Class

Let’s describe the properties in this class.

$per_page = This variable represents how many rows will be responded. ıf the request has a per_page variable, we use that if not then we have a default value for this as 10.

$page = This variable represents for which rows group will be responded. For example, We have 100 rows in our DB and responses 10 rows per request. 100 / 10 = 10. This means is we have 10-page group. $page variable will be used for this.

$sort = This variable represents the sorting parameter. For example from newer to older or from older to newer.

In our class, we got the values and respond as object (cast) data.

Now, we can use it in a controller as an example.

Paginate Query

(If you don’t know about Laravel Resources, you can check this link to get learn more about it).

As you can see above example, We used the paginated data directly. If you run our example, you will see similar data in. your response as below.

”pagination”: {
”total”: 11
”count”: 10
”per_page”: 10
”current_page”: 1
”total_pages”: 2
}

That’s it all. You can use your PaginateData class in your project everywhere you want and you can respond to paginated data for API.

If you have any questions or suggestions, please contact me. We can help each other to increase our skills.

Resources :

Enver ŞANLI

Web Developer, Social Thinker & Farmer

--

--