Skip to content

Instantly share code, notes, and snippets.

@straube
Last active October 12, 2016 06:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save straube/e52ddc27759aa97591d9 to your computer and use it in GitHub Desktop.
Save straube/e52ddc27759aa97591d9 to your computer and use it in GitHub Desktop.
Laravel 5 pagination with grouping functions
// 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