Customizing API Resource Pagination Structure

RMAG news

We have been in the same boat, trying to figure out customizing the pagination structure that was returned from the resource or resource collection. Records are wrapped in data key with additional links and meta that might be unnecessary or want to modify for a different scenario.

Before Laravel 10, you need extra steps to create base resource class that extends JsonResource, modify the collection method from the JsonResource and stuffs. Check this github discussion to modify the structure.

Starting from Laravel 10, there is a method called paginationInformation that can customize pagination data structure. All you have to do is define the method on the resource collection and modify the structure.

As docs per se

This method will receive the $paginated data and the array of $default information, which is an array containing the links and meta keys:

public function paginationInformation($request, $paginated, $default)
{
$default[‘pagination’][‘current_page’] = $default[‘meta’][‘current_page’];
$default[‘pagination’][‘last_page’] = $default[‘meta’][‘last_page’];
$default[‘pagination’][‘per_page’] = $default[‘meta’][‘per_page’];
$default[‘pagination’][‘total’] = $default[‘meta’][‘total’];

unset($default[‘links’]);
unset($default[‘meta’]);
}

The JSON response structure will be

{
“data”: [
{},
{}
],
“pagination”: {
“current_page”: “”,
“last_page”: “”,
“per_page”: “”,
“total”: “”
}
}

You may create a base class, define the function and extends the class from resource collection class to prevent code duplication.

<?php

namespace AppHttpResources;

use IlluminateHttpResourcesJsonResourceCollection;

class BaseResourceCollection extends ResourceCollection
{
public function paginationInformation($request, $paginated, $default)
{
$default[‘pagination’][‘current_page’] = $default[‘meta’][‘current_page’];
$default[‘pagination’][‘last_page’] = $default[‘meta’][‘last_page’];
$default[‘pagination’][‘per_page’] = $default[‘meta’][‘per_page’];
$default[‘pagination’][‘total’] = $default[‘meta’][‘total’];

unset($default[‘links’]);
unset($default[‘meta’]);

return $default;
}
}

<?php

namespace AppHttpResources;

use IlluminateHttpRequest;

class UserCollection extends BaseResourceCollection
{
public function toArray(Request $request): array
{
return parent::toArray($request);
}
}

Happy Tinkering ✌️

Leave a Reply

Your email address will not be published. Required fields are marked *