2017-05-28 88 views
0

我正在尝试评估auth用户的角色数组。 100和102是我想检查的角色值。如果Auth用户有其中一个,则返回true。这可能吗?这是我到目前为止的代码:检查Auth用户角色ID是否与Laravel中的数组匹配

if (Auth::user()->role_id == ([100, 102]) { 
//process code here. A lot of code. 
} 

我不想重复检查一次一个作为处理代码是很多,会使文件冗长。

+0

https://laravel.com/docs/5.4/helpers#method-array-has – Kyslik

+0

与[in_array]去(http://php.net/in_array)? – hassan

回答

2

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()) 

甚至在刀片观点:

@if (isAdmin()) 
+0

这可以通过服务提供商完成吗? –

+0

@EdenWebStudio究竟是什么? –

+0

当你在链接中回答时,你需要将助手文件添加到作曲者自动载入中。它是否可以在服务提供商中使用公共功能注册? –

1
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. 
} 
相关问题