Using limit parameter in paginate function

你说的曾经没有我的故事 提交于 2020-08-04 08:55:28

问题


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?


回答1:


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.




回答2:


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
);



回答3:


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);




回答4:


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.




回答5:


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.



来源:https://stackoverflow.com/questions/43473707/using-limit-parameter-in-paginate-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!