dtxpz8785 2017-05-28 10:55
浏览 94
已采纳

检查Auth User角色id是否与Laravel中的数组匹配

I am trying to evaluate an array of roles for an auth user. 100 and 102 are the role values I want to check. If the Auth user has one of these then return true. Is this possible? Here is my code so far:

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

I don't wish to repeat and check one at a time as the processing code is a lot and will make file lengthy.

  • 写回答

2条回答 默认 最新

  • doutu3352 2017-05-28 11:01
    关注

    in_array() will definitely work for you:

    if (in_array(auth()->user()->role_id, [100, 102]))
    

    In this case, you could also define a global helper to check if current user belongs to some role or role group:

    if (! function_exists('isAdmin')) {
        function isAdmin()
        {
            return in_array(auth()->user()->role_id, [100, 102]);
        }
    }
    

    Then you'll be able to use this helper in controllers, models, custom classes etc:

    if (isAdmin())
    

    And even in Blade views:

    @if (isAdmin())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?