Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.