Pooriya Mostaan
Pooriya Mostaan

Reputation: 405

how to show just Admin name from users table in laravel

i have a user table :

user table

and i have a realtion between user and roles :

role Model :

public function users()
{
    return $this->belongsToMany(User::class);
}

user Model :

public function roles()
{
    return $this->belongsToMany(Role::class);
}

and i have view for show users like this :

<select class="col-12 border mt-2 pt-2" name="reciever">
        @foreach($users as $user)
                <option value="">{{ $user->name }}</option>
        @endforeach
</select>

and this is controller :

$users = User::all();
return view('Form1.add', compact('users'));

but in view, i want to show just user with role Admin, how can i do this ?

this is role table :

role table

and this is pivot table between user and role like this :

pivot table between users and roles

i just want to show user with Admin role.

Upvotes: 1

Views: 1347

Answers (1)

Tim Lewis
Tim Lewis

Reputation: 29258

You need to use the whereHas() method to query your User records against their assigned Role record(s) (via the roles() relationship):

https://laravel.com/docs/7.x/eloquent-relationships#querying-relationship-existence

$adminUsers = User::whereHas('roles', function ($subQuery) { 
  $subQuery->where('name', 'Admin');
}->get();

Alternatively, you can query the Role for it's User records (via the users() relationship):

$adminUsers = Role::where('name', 'Admin')->firstOrFail()->users;

Either approach will return you the User record(s) associated with your Admin Role

Upvotes: 1

Related Questions