-1

在我的 laravel 8 iam 中定义门但是有一些问题我的门只接受一个模型名称是管理员当我尝试检查另一个模型名称时出现错误显示

这是我的 authserviceprovider

<?php

命名空间应用\提供者;

使用 App\Models\Admin\Role;使用 Illuminate\Foundation\Support\Providers\AuthServiceProvider 作为 ServiceProvider;使用 Illuminate\Support\Facades\Gate;

class AuthServiceProvider extends ServiceProvider { /** * 应用程序的策略映射。* * @var 数组 */ protected $policies = [ // 'App\Models\Model' => 'App\Policies\ModelPolicy', ];

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();
    
    Gate::define('isAdmin', function(Role $role) {

        if ($role->role === 'Admin') {
            return true;
        } else {
            return false;
        }
    });
}

}

这是控制器

 public function index(Role $role)
{
    if (!Gate::allows('isAdmin', $role)) 
    {
        abort(403);
    }

    $users = Admin::with('roles')->get();
    return view('Admin.user.index', compact('users'));
}

错误信息

TypeError

App\Providers\AuthServiceProvider::App\Providers{closure}():参数 #1 ($role) 必须是 App\Models\Admin\Role 类型,App\Models\Admin 给定,在 D:\xampp\htdocs 中调用\education\vendor\laravel\framework\src\Illuminate\Auth\Access\Gate.php 在第 477 行 http://127.0.0.1:8000/admin/users

4

1 回答 1

0

Gate主要用于授权登录用户。如果您需要在任何特定模型中授权,则使用策略

所以在 我们得到登录user instance作为自动回调

所以在你的情况下,代码将是这样的

/**
 * Register any authentication / authorization services.
 *
 * @return void
 */
public function boot()
{
    $this->registerPolicies();

    Gate::define('isAdmin', function($user) {
       return $user->role->name === 'Admin';
    });
}

然后在控制器中

public function index(Role $role)
{
    abort_if(!Gate::allows('isAdmin'));

    $users = Admin::with('roles')->get();
    return view('Admin.user.index', compact('users'));
}
于 2021-04-27T07:15:39.513 回答