2017-10-17 67 views
3

從我的控制器中,我想選擇所有具有「客戶端」角色的用戶。如何根據用戶在Laravel 5中的角色來選擇用戶?

我有一個用戶模型和示範作用。角色屬於許多用戶,用戶屬於許多角色。

我已經建立了我的模型,並有在模型實例級了一些輔助功能,用於獲取角色和用戶

下面是用戶和角色數據庫模型:

應用程序/ user.php的

class User extends Authenticatable 
{ 
    use Notifiable; 

    protected $fillable = [ 
     'name', 'email', 'password', 
    ]; 

    protected $hidden = [ 
     'password', 'remember_token', 
    ]; 

    // User belongs to many roles 
    public function roles() 
    { 
     return $this->belongsToMany('App\Role')->withTimestamps(); 
    } 

    // whitelist specific roles 
    // reject if user does not have given roles 
    public function authorizeRoles($roles) 
    { 
     if ($this->hasAnyRole($roles)) { 
      return true; 
     } 

     abort(401, 'This action is unauthorized.'); 
    } 

    // Check if a user has a role 
    public function hasRole($role) 
    { 
     if ($this->roles()->where('name', $role)->first()) 
     { 
     return true; 
     } 

     return false; 
    } 

    // Pass in string or array to check if the user has a role 
    public function hasAnyRole($roles) 
    { 
     if (is_array($roles)) { 
     foreach ($roles as $role) { 
      if ($this->hasRole($role)) { 
      return true; 
      } 
     } 
     } else { 
     if ($this->hasRole($roles)) { 
      return true; 
     } 
     } 
     return false; 
    } 
} 

應用程序/ Role.php:

class Role extends Model 
{ 
    public function users() 
    { 
     return $this->belongsToMany('App\User')->withTimestamps(); 
    } 
} 

我有一個create_users_tablecreate_roles_table遷移和create_role_user_table透視表。每個角色都有一個ID,名稱和說明。每個用戶都有一個ID,名稱,電子郵件和密碼。

我想由具有所謂的「客戶」角色的所有用戶進行過濾。

在我的控制器方法我打電話的角色,但它不工作,因爲它是一個實例方法:

// Display admin dashboard 
public function admin(Request $request) 
{ 
    // check to make sure user is an admin 
    $request->user()->authorizeRoles('admin'); 

    // Display all users that have the role "client" 
    // ***** section that does not work ******** 
    $users = User::all()->roles()->where('name', 'client')->get(); 

    return view('admin', compact('users')); 

} 

我怎樣才能填充,只有誰擁有名稱爲「客戶端角色的用戶的$users變量「?

+0

嘗試去另一個方向。獲取名稱爲客戶端的所有角色,然後獲取所有匹配的用戶。 – aynber

+0

您還可以查看[查詢關係(https://laravel.com/docs/master/eloquent-relationships#querying-relations)Laravel的文檔,看看是否有任何的方法還有爲你工作。 – aynber

回答

4

使用whereHas()方法:

User::whereHas('roles', function ($q) use ($roleName) { 
    $q->where('name', $roleName); 
})->get(); 
+1

效果很好。設置'$ roleName ='client';'或填充函數爲'function($ q){$ q-> where('name','=','client'); '謝謝! –

相關問題