Last active
October 12, 2016 06:17
-
-
Save straube/e52ddc27759aa97591d9 to your computer and use it in GitHub Desktop.
Laravel 5 pagination with grouping functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Build your query as usual, but don't use the paginate() method at the chain | |
// end. | |
$query = User::select([ 'users.*', DB::raw('count(roles.id) as roles_count') ]) | |
->join('user_roles', 'users.id', '=', 'roles.user_id') | |
->groupBy('users.id') | |
->having('roles_count', '>', 0); | |
// Due a bug in Eloquent, we need to build the paginator manually. | |
// | |
// For more details refer to: | |
// http://stackoverflow.com/questions/19349397 | |
$sub = clone $query; | |
$total = DB::table(DB::raw(sprintf('(%s) as `sub`', $sub->toSql()))) | |
->mergeBindings($sub->getQuery()) | |
->count(); | |
$perPage = 20; | |
$query->forPage( | |
$page = Paginator::resolveCurrentPage(), | |
$perPage | |
); | |
$list = new LengthAwarePaginator($query->get(), $total, $perPage, $page, [ | |
'path' => route('user.index'), | |
]); | |
// You may (optionally) add the current request parameters to the pagination | |
// links | |
$list->appends($request->all()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment