Eloquent pagination result does not include data, next_page_url and other parameters

Viewed 26

The pagination is like this:

 Qitem::filter(Request::get("search") ?: "")
                ->withUserNames()
                ->withTrashed()
                ->paginate(10)
                ->onEachSide(1)
                ->withQueryString()

The returned data is different what is expected (even according to the docs): The returned result

According to docs, there should be other attributes like prev_page_url, next_page_url, and instead of items, there should be a data attribute, containing the data from the table. It even behaves so if I simplify the query like:

Qitem::paginate(10)

Has anybody experienced similar phenomena? Any suggestions? Thanks in advance.

1 Answers

For the purposes which response do you need, you can do it like:

JSON response

Create resource:

php artisan make:resource QItemResource

More about resources in the docs

Next in your controller:

$items = Qitem::filter(Request::get("search") ?: "")
                ->withUserNames()
                ->withTrashed()
                ->paginate(10)
                ->onEachSide(1)
                ->withQueryString();

return QItemResourec::collection($items);

And you will get next_page_url, prev_page_url & data.

Collection

Just simply collect paginated data with collect().

$items = Qitem::filter(Request::get("search") ?: "")
                ->withUserNames()
                ->withTrashed()
                ->paginate(10)
                ->onEachSide(1)
                ->withQueryString();

dd(collect($items));
Related