【问题标题】:Argument 1 passed to App\Models\User::hasAnyRoles() must be of the type array, string given传递给 App\Models\User::hasAnyRoles() 的参数 1 必须是数组类型,给定字符串
【发布时间】:2021-10-18 08:59:20
【问题描述】:

我想限制管理员访问某些页面,并在运行我的代码后收到此错误: 传递给 App\Models\User::hasAnyRoles() 的参数 1 必须是数组类型,给定字符串,在第 33 行的 F:\Main Server\htdocs\voskillproject\app\Providers\AuthServiceProvider.php 中调用(查看:F :\Main Server\htdocs\voskillproject\resources\views\backend\adminsidebar.blade.php)

这是我的用户模型

public function roles(){
    return $this->belongsToMany('App\Models\Role');

}

/**
 * check if the user has a role
 * @param string $role
 * @return bool
 */
public function hasAnyRole(string $role)
{
    return null !== $this->roles()->where('Role_name',$role)->first();
}

/**
 * check if the user has any given role
 * @param array $role
 * @return bool
 */
public function hasAnyRoles(array $role)
{
    return null !== $this->roles()->whereIn('Role_name',$role)->first();
}

这是我注册门的 authserviceprovider

  Gate::define('is-admin',function($user)
  {
    return $user->hasAnyRoles('Super Admin','Company Manager');
  }); 

这里是导航栏部分

  @can('is-admin')
    <li class="nav-item {{ 'admin/roles'==request()->path()?'active':' ' }}">
      <a class="nav-link" href="{{ route('roles.index') }}">
        <i class="mdi mdi-view-headline menu-icon"></i>
        <span class="menu-title">Roles</span>
      </a>
    </li>
  @endcan

我不明白我的代码哪里做错了

【问题讨论】:

  • hasAnyRoles() 唯一定义的参数是array $role,那么为什么要通过hasAnyRoles('Super Admin','Company Manager'); 向它传递2 个参数呢?那应该是hasAnyRoles(['Super Admin','Company Manager']);...你的错误很清楚。
  • 是的,我让你明白了。实际上你的答案是对的,我忘了把它做成一个数组
  • 别担心,它发生了????您在下面的回答也有些正确;你可以做$user-&gt;hasAnyRole('Super Admin') || $user-&gt;hasAnyRole('Company Manager'),相当于$user-&gt;hasAnyRoles(['Super Admin', 'Company Manager']);第二种方法更简洁,使用的数据库调用更少,但它们都可以工作。

标签: laravel-8 laravel-gate


【解决方案1】:

我在 authserviceprovider 中找到了解决方案,而不是 hasAnyRoles,它应该是 hasAnyRole

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-22
    • 2020-01-06
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多