@giagara Just return the resources from your controller. You don’t need that macro. You also don’t need to include a success key in response bodies; that’s what HTTP status codes are for.
Oct 4, 2021
4
Level 1
Response marco with api resource and model paginate
Description:
When exposing data trough response macro with an API resource collection with a pagination data, the json response is not containing the pagination's informations.
Steps To Reproduce:
Link to a repository: github.com/giagara/marco-apiresource-bug
- Add response macro to AppServiceProvider
Response::macro('success', function ($data) {
return response()->json([
'status' => 1,
'content' => $data
]);
});
- Create a UserResource (collection)
php artisan make:resource UserResource -c
public function toArray($request)
{
return parent::toArray($request);
}
- Call the resource in the macro with pagination (in the route for instance):
Route::get('/', function () {
return response()->success(new UserResource(User::paginate()));
});
Expected result:
{
"status": 1,
"content": {
"data": [
{
"id": 1,
"name": "Alan Bartell",
"email": "[email protected]",
"email_verified_at": "2021-10-04T07:01:08.000000Z",
"created_at": "2021-10-04T07:01:08.000000Z",
"updated_at": "2021-10-04T07:01:08.000000Z"
},
{
"id": 2,
"name": "Dr. Karlee Little",
"email": "[email protected]",
"email_verified_at": "2021-10-04T07:01:08.000000Z",
"created_at": "2021-10-04T07:01:08.000000Z",
"updated_at": "2021-10-04T07:01:08.000000Z"
},
...
],
"links": {
"first": "http://127.0.0.1:8000?page=1",
"last": "http://127.0.0.1:8000?page=7",
"prev": null,
"next": "http://127.0.0.1:8000?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 7,
"links": [
{
"url": null,
"label": "« Previous",
"active": false
},
...
],
"path": "http://127.0.0.1:8000",
"per_page": 15,
"to": 15,
"total": 100
}
}
}
Actualresult:
{
"status": 1,
"content": [
{
"id": 1,
"name": "Alan Bartell",
"email": "[email protected]",
"email_verified_at": "2021-10-04T07:01:08.000000Z",
"created_at": "2021-10-04T07:01:08.000000Z",
"updated_at": "2021-10-04T07:01:08.000000Z"
},
{
"id": 2,
"name": "Dr. Karlee Little",
"email": "[email protected]",
"email_verified_at": "2021-10-04T07:01:08.000000Z",
"created_at": "2021-10-04T07:01:08.000000Z",
"updated_at": "2021-10-04T07:01:08.000000Z"
},
...
]
}
Please or to participate in this conversation.