2017-05-28 55 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. 
} 
相關問題