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 paginate() $perPage parameter as callable with access to $total #42429

Merged
merged 2 commits into from
May 19, 2022

Conversation

Niush
Copy link
Contributor

@Niush Niush commented May 18, 2022

Feature adds ability to have $perPage as a callback closure with access to $total.

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

// Now (saves extra query and builder code):
DB::table('products')->paginate(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.

Example, in a list of products, with above snippet, it will load all ~110 products if there is less then 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 in second page.

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

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

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

@Niush Niush marked this pull request as ready for review May 18, 2022 17:33
@johanrosenson
Copy link
Contributor

Nitpicking, but your last example need to use ceil instead of round to get at most 4 pages, otherwise something like total = 101 will be 5 pages.

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.

3 participants