Reputation: 178
So I have a user
table, a role
table and an intermediate table for those 2, user_role
. It's a many-to-many relationship between the first 2 tables.
I want to return the count of the users which have a specific role but I can't seem to get it right.
My migrations:
user:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('email')->unique();
$table->string('username')->unique();
$table->string('password');
});
role:
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name', 40);
$table->string('description', 255);
});
user_role:
Schema::create('user_role', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('user_id');
$table->integer('role_id');
});
Relationship between them:
public function users(){ //in role model
return $this->belongsToMany('App\User', 'user_role', 'role_id', 'user_id')->withTimestamps();
}
public function roles(){ //in user model
return $this->belongsToMany('App\Role', 'user_role', 'user_id', 'role_id')->withTimestamps();
}
Role Seeder:
public function run()
{
Role::create([
'id' => 1,
'name' => 'Admin',
'description' => 'Admin User.'
]);
Role::create([
'id' => 2,
'name' => 'Vendor',
'description' => 'Vendor User.'
]);
Role::create([
'id' => 3,
'name' => 'User',
'description' => 'Simple User.'
]);
}
in controller:
public function adminDashboard(){
$users = User::all();
return view('admin.dashboard')->withUsers($users);
}
in view:
{{ $users->count() }}
This obviously, returns the total count of users in user table. Any ideas on how to return the count of users which have a specific role?
Upvotes: 0
Views: 504
Reputation: 9465
use $role->users()->count()
To iterate over the roles and display the count of users, you can use this:
public function adminDashboard(){
$roles = App\Role::all();
return view('admin.dashboard', compact('roles'));
}
In your dashboard view:
@foreach ($roles as $role)
<p>Role {{ $role->name }} has {{ $role->users()->count() }} users</p>
@endforeach
Upvotes: 1