Recently I have implemented Laravel pagination with resources. But the problem is when I add some custom attributes or wrappers, pagination metadata gets lost. without wrappers or custom attributes, working fine.
Resource class
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
];
}
}
Controller function
public function index()
{
return response()->json([
'success' => 'true',
'message'=>'Request successful',
'result' => UserResource::collection(User::paginate(3))
]);
}
Output
{
"success": "true",
"message": "Request successful",
"result": [
{
"id": 1,
"name": "System Admin",
"email": "[email protected]"
}
]
}
^ pagination data missing
Expectation
{
"success": "true",
"message": "Request successful",
"result": {
"data": [
{
"id": 1,
"name": "System Admin",
"email": "[email protected]"
},
{
......
}
],
"links": {
"first": "http://localhost:8080/api/v1/user?page=1",
"last": "http://localhost:8080/api/v1/user?page=4",
"prev": null,
"next": "http://localhost:8080/api/v1/user?page=2"
},
"meta": {
"current_page": 1,
"from": 1,
"last_page": 4,
"path": "http://localhost:8080/api/v1/user",
"per_page": 3,
"to": 3,
"total": 11
}
}
}
Thanks.
I have solved that issue using
return response()->json([
'success' => 'true',
'message'=>'Request successful',
'result' => UserResource::collection(User::paginate(3))->response()->getData()
]);
Very simple solution
$data = UserResource::collection(User::paginate(3))->resource;
return response()->json([
'success' => 'true',
'message'=>'Request successful',
'data' => $data
]);
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