How to Implement Pagination in Laravel REST APIs
Building a REST API requires handling data collection differently than building a standard view-based application. When you request a list of resources, such as categories, clients expect two things: a list of items and metadata about the collection. Metadata includes the total count of records available, the number of items returned on the current page, and the links to navigate between pages.
In your specific scenario, you have 30 categories in the database and want to display 10 per page. This results in a ?page=1 response containing 10 items, a ?page=2 response with the next 10, and so on. The core issue in your current implementation is that you are calling $getCategories = Category::paginate(); without passing a parameter to define the number of items per page. By default, Laravel uses 15 items per page, but more importantly, your subsequent loop ignores the pagination metadata entirely.
You are currently iterating over the collection and manually constructing an array for every item. This approach discards the links, from, to, last_page, and total properties provided by the Eloquent paginator class. If you return this structure directly as JSON, your client application will not be able to render the pagination controls because they lack the necessary navigation data.
To fix this, you must explicitly pass the number of items per page to the paginate() method. You can do this by chaining the call with an integer argument:
$page = request('page', 1);
$perPage = 10;
$getCategories = Category::paginate($perPage);
Once you have the paginated collection, you should not manually loop through it to build a generic array. Instead, leverage Laravel's built-in JSON serialization capabilities. When you encode the paginator object directly into JSON using response()->json(), Laravel automatically includes the pagination metadata in the response body. This allows your frontend to easily access $data->links or $data->total.
Here is how you can refactor your controller method:
use Illuminate\Http\Request;
public function index(Request $request)
{
// Define the number of items per page, defaulting to 10 if not specified
$perPage = request('per_page', 10);
// Optional: Add simple filtering or sorting here if needed
// $categories = Category::where('status', 'active')->get();
// Paginate the query
$paginatedCategories = Category::paginate($perPage);
// Return the paginator as JSON.
// Laravel automatically includes the 'data' array and pagination metadata.
return response()->json($paginatedCategories, 200);
}
By returning the paginator object directly, you avoid the overhead of manually mapping fields unless you have specific needs to transform the data structure. However, if your frontend expects a flat JSON object with separate status and message keys (as seen in your original code), you can wrap the paginator inside that structure while still preserving the pagination properties:
if ($paginatedCategories->total() > 0) {
return response()->json([
'status' => true,
'message' => 'Categories list',
'data' => $paginatedCategories, // The paginator object retains its metadata
], 200);
}
return response()->json([
'status' => false,
'message' => 'Category is not found.',
], 404);
This approach ensures that even when wrapped, the data property remains an instance of LengthAwarePaginator. Your client can then access $response.data.data for the list and $response.data.meta (or similar keys depending on your wrapper) for navigation. Note that in some cases, it is cleaner to transform the data into a plain array if you need to remove relationships or add computed fields before sending the response.
If you are using API Resources, which is the recommended pattern for building clean APIs, you can define a resource to handle the transformation and serialization simultaneously:
// app/Http/Resources/CategoryResource.php
public static function collection($resource)
{
return new self;
}
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'image' => url('/').'/public/assets/images/category/'.$this->image,
];
}
public function with($request)
{
return [
'total' => $this->paginator->total(),
];
}
Using API Resources allows you to control exactly what fields are exposed in the JSON response while keeping the pagination logic separate from your data mapping. This separation of concerns is a significant advantage as your application grows and requires more complex data transformations.
