1

i'm using entrust package Basically I just want to count users based on roles something like this:

    $users = User::whereHas('roles')->count();
    dd($users);

naturally what i'm getting is the count of users with roles, but what i'm trying to get is something like this..

expected

**roles          count**

 admin             4
 user              2
$role_name     $User_withthisRole_count

Edited: i want something dynamic, i don't want to add roles manually

not sure what to do..

6 Answers 6

7

Use withCount():

$roles = Role::withCount('users')->get();
foreach($roles as $role) {
    // $role->users_count
}
Sign up to request clarification or add additional context in comments.

Comments

1
$users = User::where('roles','user')->count();
$admins = User::where('roles','admin')->count();

1 Comment

i want something more dynamic, i don't want to add roles manually, the result should be based on {{ $role->display_name }}
1

Use Laravel groupBy

User::select('roles', DB::raw('count(*) as count'))
->groupBy('roles')
->get();

2 Comments

Column not found: 1054 Unknown column 'roles' in 'field list'
what is the column name for roles
1

You could do something like this:

    $roles = Role::pluck('name');

    foreach ($roles as $roleName) {
        $userCount = User::whereHas('roles', function($query) use($roleName) {
            $query->where('name', $roleName);
        })->count();
    }

2 Comments

your answer got me closest as much as I've found, still there were error Unknown column 'roles' in 'where clause' (SQL: select count(*) as aggregate from users where roles = (select * where name = admin))
Maybe you need to add this: $roles = Role::pluck('name')->toArray();. According to entrust documentation, you also may do this $admins = User::withRole('admin')->get(); // or maybe with a relationsship $company->users()->withRole('admin')->get();
1

i had to do a raw query, thanks all for the help

DB::select( DB::raw("select name,count(name) AS count,display_name from roles a,
role_user b where a.id=b.role_id group by name") )

Comments

0

This worked for me

$roles = User::where('role_id',$roles->id)->count();

My relation is a one to many

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.