Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel resource pagination meta data missing

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.

like image 712
Nishantha Kumara Avatar asked Feb 03 '26 16:02

Nishantha Kumara


2 Answers

I have solved that issue using

return response()->json([
       'success' => 'true',
       'message'=>'Request successful',
       'result' => UserResource::collection(User::paginate(3))->response()->getData()
      ]);
like image 63
Nishantha Kumara Avatar answered Feb 05 '26 06:02

Nishantha Kumara


Very simple solution

$data = UserResource::collection(User::paginate(3))->resource;
    
     return response()->json([
               'success' => 'true',
               'message'=>'Request successful',
               'data' => $data
              ]);
like image 21
khatib Avatar answered Feb 05 '26 06:02

khatib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!