【问题标题】:Check if Auth User role id matches array in Laravel检查 Auth User 角色 id 是否与 Laravel 中的数组匹配
【发布时间】:2017-05-28 10:55:05
【问题描述】:

我正在尝试评估身份验证用户的一系列角色。 100 和 102 是我要检查的角色值。如果 Auth 用户拥有其中之一,则返回 true。这可能吗?到目前为止,这是我的代码:

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

我不希望一次重复并检查一个,因为处理代码很多并且会使文件冗长。

【问题讨论】:

标签: php laravel


【解决方案1】:

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

【讨论】:

  • @EdenWebStudio 究竟是什么?
  • 在您在链接中回答时,您会将 Helper 文件添加到 composer autoload。在服务提供者中使用公共函数注册有用吗?
  • @EdenWebStudio 是的,如果您在服务提供者中包含帮助文件,它将起作用。但我认为更好的方法是使用composer.json 自动加载文件。
【解决方案2】:
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. 
}

【讨论】:

    猜你喜欢
    • 2020-10-27
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多