Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Adds ability to have simplePaginate() $perPage parameter as callable with access to $total #42840

Closed
wants to merge 1 commit into from

Conversation

michaelnabil230
Copy link
Contributor

The feature adds the ability to have $perPage as a callback closure with access to $total.

// Previously:
$total = DB::table('products')->count();
DB::table('products')->simplePaginate($total <= 110 ? 110 : 100);

// Now (saves extra query and builder code):
DB::table('products')->simplePaginate(function ($total) {
    return $total <= 110 ? 110 : 100;
});

There might be a scenario when you want to use different/dynamic per page depending on the total count of records.

For example, in a list of products, with the above snippet, it will load all ~110 products if there are less than or equal to 110 products in total. Else, defaults to 100 as usual. So that, there won't be just a few items sitting around on the second page.

Similarly, if we want to have exact 4 pages, we can provide a dynamic per page value like such:

Product::oldest()->simplePaginate(function ($total) {
    return ceil($total / 4); // Will always have at most 4 pages in total
});

And, of course, the normal simplePaginate(10) will still work.

This PR is a same this PR #42429 put in simplePaginate

@taylorotwell
Copy link
Member

This seems to break the simple pagination concept in general - you are running a count.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants