Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Coolone3000's avatar

Pagination data missing from api resource.

  • Laravel Version: 7.8.1
  • PHP Version: 7.4.2
  • Database Driver & Version: MySql & 5.7

Description:

When sending an eloquent query to an api resource with pagination the pagination data is missing from the result.

Laravel 6.x

{
  "current_page": 1,
  "data": [
    {
      "id": 10000196,
      "name": "John Doe",
    }
  ],
  "first_page_url": "http://www.mysite.com/users?page=1",
  "from": 1,
  "next_page_url": "http://www.mysite.com/users?page=2",
  "path": "http://www.mysite.com/users",
  "per_page": 1,
  "prev_page_url": null,
  "to": 1
}

Laravel 7.x

[
  {
    "id": 10000196,
    "name": "John Doe",
  }
]

Steps To Reproduce:

Using a fresh laravel app with the default user table and at least one user in the database.

$resource = \App\Http\Resources\User::collection(\App\User::query()->paginate(1));

dd($resource->toJson());
0 likes
5 replies
rodrigo.pedra's avatar
Level 56

It seems this is due to changes here: https://github.com/laravel/framework/pull/30801

So by that PR description, previously when calling ->toJson() the call would be forwarded to the underlying resource.

So you might expect a different output from 7.x resources when using paginated data. One difference is that paginalition links are under a meta property. Actually this was already done in previous versions when returning the resource as a response instead of calling its ->toJson() method.

You can try doing this:

dd($resource->response()->getData())

This will convert the Resource to a Response object and getData will use json_decode to decode the response's content back.

If you want the payload to be decoded as an associative array use this:

dd($resource->response()->getData(true))

And if you want the raw decoded JSON payload use this instead:

dd($resource->response()->getContent())
6 likes
progalaa's avatar

To make your code clean make a PaginationResource to be used across different collections and make single place for editing pagination details

then inside any resource add your Pagination resource as follow

this is Pagination resource

public function toArray($request) : Array
    {
        return [
            'total' => $this->total(),
            'count' => $this->count(),
            'per_page' => $this->perPage(),
            'current_page' => $this->currentPage(),
            'total_pages' => $this->lastPage()
        ];
    }

and add it to any other collection like this

 public function toArray($request) : Array
    {
        $pagination = new PaginationResource($this);

        return [
            'templates' => $this->collection,
            $pagination::$wrap => $pagination,
        ];
    }

mtzrmzia's avatar

This don't work for me :( i'm using Laravel 8

Please or to participate in this conversation.