Josh Petitt
Josh Petitt

Reputation: 9579

Laravel Eloquent paginate how to query pagination parameters?

I have a Laravel project that has an API. Some endpoint controllers use pagination for the index.

I would like to expose the pagination parameters to the client. The reason is so they wouldn't have to always ask for the first item, just to figure out how many items per page there will be (for instance if the client wants to skip the first X items for some reason).

I've tried paginate(0) but this gives the default of 16 items.

Is there an easy built-in way to do this?

Upvotes: 2

Views: 1920

Answers (1)

Erick Patrick
Erick Patrick

Reputation: 91

You could convert the Paginator results to JSON. Doing so, you'll get some meta data, including the total number of items, number of pages, current page, etc.

According to the linked page, if we have a route like this:

Route::get('users', function () {
    return App\User::paginate();
});

It would return something like this:

{
   "total": 50,
   "per_page": 15,
   "current_page": 1,
   "last_page": 4,
   "next_page_url": "http://laravel.app?page=2",
   "prev_page_url": null,
   "from": 1,
   "to": 15,
   "data":[
        {
            // Result Object
        },
        {
            // Result Object
        }
   ]
}

I think that this would be what you're looking for.

Hope it helps you.

Upvotes: 2

Related Questions