0

I'm trying to select all users for a company. But only users who has "admin" role status (Entrust, etc.).

User::where('company_id', Auth::user()->company_id)->hasRole('admin')->get();

The above is throwing an error. Left a bit lost on how to run such a query. Where am I going wrong with this? Very little documentation on Entrust.

Mike Barwick
  • 6,288
  • 6
  • 51
  • 76

2 Answers2

1

Think you need to get all the users having the company_id first

$users = User::where('company_id', Auth::user()->company_id)->get();

Then loop through $users and check hasRole()

foreach ($users as $user) {
        if($user->hasRole('admin')){
        //user is admin
    }
}

UPDATE

This might be a dirty solution but you can try to do a manual query

$admin = DB::table('role_user')
        ->join('users', 'users.id', '=', 'role_user.user_id')
        ->join('roles', 'roles.id', '=', 'role_user.role_id')
        ->where('roles.name', 'admin')->get();
Saad
  • 1,155
  • 3
  • 16
  • 36
1

You can use plain Eloquent for this. The whereHas method would generate one query:

$users = User::where('company_id', Auth::user()->company_id)
             ->whereHas('roles', function($query) {
                 $query->where('name', 'admin');
             })->get();

Or, you can just get the roles and then get all of that role's users. This would generate two queries, but ultimately achieve the same thing.

$users = Role::where('name', 'admin')
             ->first()
             ->users()
             ->where('company_id', Auth::user()->company_id)
             ->get();
Thomas Kim
  • 15,326
  • 2
  • 52
  • 42