私のコントローラからは、「クライアント」の役割を持つすべてのユーザーを選択したいと考えています。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'));
}
"?
は、他の方向に行くお試しください。 nameがクライアントであるすべてのロールを取得し、一致するすべてのユーザーを取得します。 – aynber
また、Laravelの[クエリ関係](https://laravel.com/docs/master/eloquent-relationships#querying-relations)のドキュメントをチェックして、そこにあるメソッドがあるかどうかを確認することもできます。 – aynber