简体   繁体   中英

Return count of a table's column via pivot table Laravel 5.2

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM