Kritim Yantra
Jun 25, 2025
“Imagine loading 10,000 records in a mobile app — not fun, right? That’s where pagination saves the day!”
If you’re building APIs in Laravel 12, chances are you’ll run into the need for pagination. Whether you're listing blog posts, users, products, or comments — pagination keeps your API fast, clean, and user-friendly.
In this easy-to-follow guide, you'll learn how to:
Let’s dive in! 🏊♂️
Imagine you're in a library with 1,000 books. Instead of listing all the books on one long page, the librarian hands you a catalog — 10 books per page.
That’s pagination — breaking large data into small, manageable chunks.
paginate()
Let’s assume you already have a PostController
and a Post
model.
return Post::all();
return Post::paginate(10);
This will return 10 posts per page by default.
{
"current_page": 1,
"data": [
{ "id": 1, "title": "Post One", ... },
{ "id": 2, "title": "Post Two", ... }
],
"first_page_url": "http://yourapp.test/api/posts?page=1",
"last_page": 5,
"last_page_url": "http://yourapp.test/api/posts?page=5",
"per_page": 10,
"total": 50
}
That’s a lot of helpful info returned automatically!
If you're using API Resources (which you should for clean API responses), here's how to use them with pagination.
Update your index()
method:
use App\Http\Resources\PostResource;
public function index()
{
return PostResource::collection(Post::paginate(10));
}
Laravel will wrap the pagination metadata automatically, like:
{
"data": [
{ "id": 1, "title": "Hello", "content": "..." },
...
],
"meta": {
"current_page": 1,
"last_page": 5,
"per_page": 10,
"total": 50
},
"links": {
"first": "...",
"last": "...",
"prev": null,
"next": "..."
}
}
Want to change the number of items per page?
You can make it dynamic using the query string:
public function index(Request $request)
{
$limit = $request->get('limit', 10); // default = 10
return PostResource::collection(Post::paginate($limit));
}
Now you can call:
GET /api/posts?limit=5
If you only care about next/previous, use:
Post::simplePaginate(10);
This returns a lighter payload, useful for mobile apps or simple UIs.
Use Postman or your favorite API client:
GET /api/posts
GET /api/posts?page=2
GET /api/posts?limit=5&page=3
🎯 You’ll get a smaller, faster response each time.
Pagination is not just a nice-to-have — it’s essential for scalable and efficient APIs. With Laravel 12, it's super simple to implement and customize.
No comments yet. Be the first to comment!
Please log in to post a comment:
Sign in with Google