Reputation: 265
Is it possible to use 'limit' parameter in paginate() function?
I'm trying this:
$users->where(...)->limit(50)->paginate($page)
...and now, if I have 100 users in the database then the response from paginate function will be all 100 users instead of 50 (or number of users defined with limit parameter).
So, my question is: is it possible to implement limit parameter when I use paginate function?
Upvotes: 6
Views: 21785
Reputation: 983
as @patricus said it's not possible, but you can take a walk around to get what you want, it will be something like:
$users=User::where(...)->limit(50);
$users=$user->paginate(10);
this trick works for me, but after some thinking, I realized I'm really didn't need to apply this solution as pagination already limit the query. All what you need is the right query for your needs.
Upvotes: 0
Reputation: 93
If you want use limit in Laravel query then will we use offset for pagination.
First time
$users->where(...)->limit(10)->offset(0);
On next click
$users->where(...)->limit(10)->offset(10);
More next click
$users->where(...)->limit(10)->offset(20);
Upvotes: 0
Reputation: 62308
No, it's not possible to limit the query when using pagination.
Query pagination uses skip()
and limit()
internally to select the proper records. Any limit()
applied to the query will be overwritten by the pagination requirements.
If you'd like to paginate a subset of results, you will need to get the results first, and then manually create a paginator for those results.
Upvotes: 9
Reputation: 1
Use LengthAwarePaginator.
Example:
$total = 50;
$perPage = 10;
$users = $users->where(...)->paginate($page);
$users = new LengthAwarePaginator(
$users->toArray()['data'],
$users->total() < $total ? $users->total() : $total,
$perPage,
$page
);
Upvotes: 0
Reputation: 1719
By default, the current page is detected by the value of the page query string argument on the HTTP request. Of course, this value is automatically detected by Laravel, and is also automatically inserted into links generated by the paginator.
So, inform page and pagination and all should be fine.
Upvotes: -1