2

Am sending my request with perPage and page in the url. That is

url = users?page=0&perPage=10 //the get http url

So i would like to paginate my model request like and specify both page and perPage

User::paginate()

So looking in the docs i see i can add perPage but i cant see how to add the page. so from laravel documentation i see you can add the perPage like

User::paginate($request->get('perPage')) //perPage from url request

But now how do i add the page parameter to the paginate, such that i can specify page value like 0

HOw do i proceed?

I have also checked on This question but it doesnt show how to set it in an eloquent model paginate

3 Answers 3

8

The paginate method in Illuminate/Database/Eloquent/Builder has the following signature:

public function paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null)

As long as you have a page=n (n for number > 0, i.e: page=2) in your url (query string), you don't need the page number to be passed in paginate method. In case you want then, you may do it using something like the following:

$users = User::paginate(
    10, // per page (may be get it from request)
    ['*'], // columns to select from table (default *, means all fields)
    'page', // page name that holds the page number in the query string
    10 // current page, default 1
);

FYI, Laravel resolves the current page using Illuminate/Pagination/AbstractPaginator:: resolveCurrentPage method which (resolver) was set in Illuminate/Pagination/PaginationServiceProvider:: currentPageResolver method when registering the service provider.

In case you don't know, you can also omit the perPage because by default Laravel chunks by 15 records and it's set up in the base model and you can override it in your model using:

protected $perPage = 10;

So, you can just use User::paginate() which will give you 10 items/perPage.

Note: The api links are given for 5.6 but it's same in higher versions in this case (AFAIK).

Sign up to request clarification or add additional context in comments.

Comments

2

From official documentation

the current page is detected by the value of the page query string argument on the HTTP request.

Laravel handle it automatically. So you don't need do something.

Comments

1

Use ->appends() method

$users = User::paginate($request->get('perPage')); 
$users->appends($request->all());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.