Using limit parameter in paginate function
Asked Answered
A

5

6

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?

Alliber answered 18/4, 2017 at 13:32 Comment(0)
R
9

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.

Rockwood answered 18/4, 2017 at 18:39 Comment(0)
T
0

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
);
Tropic answered 17/11, 2017 at 12:1 Comment(0)
F
0

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

Foiled answered 20/3, 2020 at 12:50 Comment(0)
C
0

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.

Caret answered 21/7, 2020 at 18:6 Comment(0)
C
-1

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.

Carbolated answered 15/10, 2017 at 17:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.