2017-10-17 4 views
3

私のコントローラからは、「クライアント」の役割を持つすべてのユーザーを選択したいと考えています。Laravel 5での役割に基づいてユーザーを選択するにはどうすればよいですか?

私はUserモデルとRoleモデルを持っています。役割は多くのユーザーに属し、ユーザーは多くの役割に属します。

私は私のモデルを確立し、ここでロールとユーザー

を取得するためのモデルインスタンスレベルでいくつかのヘルパー関数を持っていましたが、ユーザーおよびロールのデータベースモデルは以下のとおりです。

アプリ/ 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_role_user_tableため create_users_table、create_roles_tableとピボットテーブルの移行を持っています。各役割にはID、名前、説明があります。各ユーザーには、ID、名前、電子メール、パスワードがあります。

「クライアント」という役割を持つすべてのユーザーにフィルタリングしたいと考えています。私のコントローラメソッドで

私は役割を呼び出そうが、それはインスタンスメソッドであるため、それは動作しません:私は名前を「クライアントとの役割を持つユーザーのみと$users変数を移入するにはどうすればよい

// 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')); 

} 

"?

+0

は、他の方向に行くお試しください。 nameがクライアントであるすべてのロールを取得し、一致するすべてのユーザーを取得します。 – aynber

+0

また、Laravelの[クエリ関係](https://laravel.com/docs/master/eloquent-relationships#querying-relations)のドキュメントをチェックして、そこにあるメソッドがあるかどうかを確認することもできます。 – aynber

答えて

4

whereHas()方法用途:

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

は素晴らしい作品です。 '$ roleName = 'client';または' pop($ name) '(' name '、' = '、' client ')のようにpopulated関数を設定します。 }「ありがとう! –

関連する問題