【发布时间】:2017-05-28 10:55:05
【问题描述】:
我正在尝试评估身份验证用户的一系列角色。 100 和 102 是我要检查的角色值。如果 Auth 用户拥有其中之一,则返回 true。这可能吗?到目前为止,这是我的代码:
if (Auth::user()->role_id == ([100, 102]) {
//process code here. A lot of code.
}
我不希望一次重复并检查一个,因为处理代码很多并且会使文件冗长。
【问题讨论】:
我正在尝试评估身份验证用户的一系列角色。 100 和 102 是我要检查的角色值。如果 Auth 用户拥有其中之一,则返回 true。这可能吗?到目前为止,这是我的代码:
if (Auth::user()->role_id == ([100, 102]) {
//process code here. A lot of code.
}
我不希望一次重复并检查一个,因为处理代码很多并且会使文件冗长。
【问题讨论】:
in_array() 绝对适合你:
if (in_array(auth()->user()->role_id, [100, 102]))
在这种情况下,您还可以定义global helper 来检查当前用户是否属于某个角色或角色组:
if (! function_exists('isAdmin')) {
function isAdmin()
{
return in_array(auth()->user()->role_id, [100, 102]);
}
}
然后你就可以在控制器、模型、自定义类等中使用这个助手了:
if (isAdmin())
甚至在 Blade 视图中:
@if (isAdmin())
【讨论】:
composer.json 自动加载文件。
As hassan said you can use in_array()
$a= Auth::user()->role_id;
$b= in_array(100, $your_array);
$c= in_array(102, $your_array);
if ( $a == $b && $a == $c ) {
//process code here. A lot of code.
}
【讨论】: