I'm using Laravel 8 to build a simple API with paginated JSON.
The output contains a "links" object into "meta" key:
{
"data": [
{
. . .
},
{
. . .
}
],
"links": {
"prev": null,
"first": "http://localhost/api/my-api?&page=1",
"next": null,
"last": "http://localhost/api/my-api?&page=2"
},
"meta": {
"from": 1,
"per_page": 400,
"total": 477,
"current_page": 1,
"last_page": 2,
"path": "http://localhost/api/my-api",
"to": 400,
"links": [
{
"url": null,
"label": "Previous",
"active": false
},
{
"url": "http://localhost/api/my-api?&page=1",
"label": 1,
"active": true
},
{
"url": "http://localhost/api/my-api?&page=2",
"label": 2,
"active": false
},
{
"url": "http://localhost/api/my-api?&page=2",
"label": "Next",
"active": false
}
]
}
}
I've not found any documentation about it; also, the official documentation doesn't report it:
How can I remove the "links" object?
It's a little bit of trickery as we don't want to touch the source code. In your Http/Controller/Api/V1
map or wherever your API collection classes exists, create a file called PaginateResourceResponseExtended.php
. Add this code to the file:
namespace App\Http\Controllers\Api\V1;
use Illuminate\Support\Arr;
use Illuminate\Http\Resources\Json\PaginatedResourceResponse;
class PaginateResourceResponseExtended extends PaginatedResourceResponse
{
/**
* Gather the meta data for the response.
*
* @param array $paginated
* @return array
*/
protected function meta($paginated)
{
return Arr::except($paginated, [
'data',
'first_page_url',
'last_page_url',
'prev_page_url',
'next_page_url',
'links' //<----- THIS!
]);
}
}
In your resource collection class, which is an extension to ResourceCollection
add this:
use App\Http\Controllers\Api\V1\PaginateResourceResponseExtended;
Inside your class you can override a ResourceCollection
method called preparePaginatedResponse
:
public function preparePaginatedResponse($request)
{
if ($this->preserveAllQueryParameters) {
$this->resource->appends($request->query());
} elseif (! is_null($this->queryParameters)) {
$this->resource->appends($this->queryParameters);
}
return (new PaginateResourceResponseExtended($this))->toResponse($request);
}
Et voilà !
Of course you could also extend the Illuminate\Http\Resources\Json\ResourceCollection;
class, change the method as described above and extend this to all your resource collections.
The protected meta
method in Illuminate\Http\Resources\Json\PaginatedResourceResponse
is what you want to change by simply adding 'links'
to the Array exceptions.
Just cross fingers the Laravel source files methods you override don't change in the next Laravel version 🙄
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With