How can I customize Laravel ResourceCollection meta and links information.
Links should include only prev,next and self instead of first,last,prev,next that is by default.
Meta should include pagination iformation like: current_page, total_items, items_per_page, total_pages instead of current_page, from, last_page, path, per_page, to, total.
This is how meta and links information looks now in JSON response:
"meta": {
"currentPage": 2,
"current_page": 1,
"from": 1,
"last_page": 3,
"path": "http://localhost:8000/api",
"per_page": 5,
"to": 5,
"total": 14
},
"links": {
"self": "http://localhost:8000/api",
"first": "http://localhost:8000/api?page=1",
"last": "http://localhost:8000/api?page=3",
"prev": null,
"next": "http://localhost:8000/api?page=2"
}
.. I want it to be something like:
"meta": {
"current_page": 1,
"total_items": 15,
"per_page": 5,
"total_pages": 3
},
"links": {
"prev": null,
"next": "http://localhost:8000/api?page=2"
"self": "http://localhost:8000/api",
}
I have not been a fan with how Laravel has implemented paginators and resources, as its difficult to do certain things like the issue that you mentioned.
Internals
Before you can customise your responses in the way you want, you first need to understand how ResourceCollections are converted to responses.
The original
toResponse
method for resource collections looks like this:If you look in further into
PaginatedResourceResponse
class you will see the following code.I recommend reading
Illuminate\Http\Resources\Json\PaginatedResourceResponse
andIlluminate\Http\Resources\Json\ResourceResponse
fully to understand what's going on.Solution 1: Create a custom PaginatedResourceResponse
One solution is to create a new class that extends
PaginatedResourceResponse
, and override thepaginationLinks
method.So it look something like:
Then you can override your
toResponse
method to look something like:You may consider overriding overriding other methods if you want to customise your response further.
Solution 2: Override
toResponse
in the ResourceCollectionInstead of overriding the
PaginatedResourceResponse
, you can just override thetoResponse
method in the ResourceCollection with a lightweight version of similar code like so:Solution 3: Override
withResponse
methodA simpler, but perhaps less powerful option is to just override the
withResponse
at the resource collection like so: