使用Auth来获取用户在数据透视表中的角色 [英] Using Auth to get the role of user in a pivot table
问题描述
我具有以下数据库结构的用户&使用数据透视表联接的角色表:
I have the following database structure a users & roles table joined using a pivot table:
用户表包含所有信息,例如电子邮件和密码,而角色表定义了不同的角色:
The users table contains all the info such as email and password, while the roles table defines the different roles :
角色表
- 1->管理员
- 2->编码器
- 3->业务员
- 4->技术
现在定义了角色到多对,因为有些编码器也被指定为管理员.其他人可能会担任推销员+管理员角色,甚至可能担任编码器+推销员.基本上,可以将多个角色分配给某人.
Now the roles are defined many-to-many because, there are some encoders that are assigned also as an admin. Others may have an salesman+admin role, or even encoder+salesman. Basically it multiple roles can be assigned to someone.
用户
- id
- 电子邮件
角色
- id
- 角色
role_user
- id
- role_id
- user_id
我知道,如果我这样做
$user = User::find(1)->email;
return $user;
结果将显示ID为1的用户的电子邮件.
the result would display the email of the user with ID 1.
我正在尝试执行$user = Auth::user()->roles;
,以便它将获得当前经过身份验证的用户的角色.
I was trying to do $user = Auth::user()->roles;
so that it will get the role of the currently authenticated user.
但是这样做会返回一个JSON,其中显示了分配给用户的所有角色.
But doing so returns a JSON which displays all the roles the user is assigned to.
我希望在过滤器中使用它来做类似的事情
I was hoping to use this in a filter, to do something like this
$user=Auth::user()->roles;
if($user == 'admin')
{
//do something
}
else
{
//you are not an admin
}
if($user == 'encoder')
{
//do something
}
else
{
//you are not an encoder
}
推荐答案
由于它是many-to-many
关系,因此当您使用以下代码时,您将在$user
中获得一个集合:
Since it is a many-to-many
relationship so you are getting a collection in the $user
when you use following code:
$user = Auth::user()->roles;
因此,您需要循环所有Role
模型,并且必须在循环中检查if($someUser->role == 'admin')
,在这种情况下,您可以这样做:
So, you need to loop all the Role
models and have to check if($someUser->role == 'admin')
within the loop and in this case you may do it like this:
$roles = Auth::user()->roles;
$isAdmin = false;
$isAdmin = !$roles->filter(function($role) {
return $role->role == 'admin';
})->isEmpty();
if($isAdmin) {
// admin...
}
此外,您可以在User
模型中添加如下方法:
Also you may add a method in your User
model like this:
// User model
public function isAdmin()
{
$isAdmin = false;
$isAdmin = !$this->roles->filter(function($item) {
return $item->role == 'admin';
})->isEmpty();
return $isAdmin;
}
因此您可以使用:
if(Auth::user()->isAdmin()) {
// admin...
}
更新:检查任何角色:
public function hasRole($role = null)
{
$hasRole = false;
$hasRole = !$this->roles->filter(function($item) {
return $item->role == $role;
})->isEmpty();
return $hasRole;
}
现在您可以使用:
if(Auth::user()->hasRole('encoder')) {
//...
}
这篇关于使用Auth来获取用户在数据透视表中的角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!