Laravel 自定义用户模型策略问题

问题描述 投票:0回答:1

我正在开发一个 Laravel 项目,其中有一个自定义用户模型(管理员模型)。我正在尝试为第三方模型创建策略,但即使从策略方法返回 true 时,我仍然遇到“操作未经授权”错误。

这是政策方法:

public function view(?Admin $admin, ThirdParty $thirdParty)
{
    return true;
}

我已在 AuthServiceProvider 中注册了策略,如下所示: 使用App\Models\ThirdParty; 使用App\Policies\ThirdPartyPolicy;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        ThirdParty::class => ThirdPartyPolicy::class,
    ];
    // ...
}

这就是我在 api.php 中应用它的方式:

Route::get('show/{id}', [ThirdPartyController::class, 'show'])->can('view', 'thirdParty');

最后,控制器动作如下所示:

public function show(Request $request, ThirdParty $thirdParty)
{
    // ...
}

我尝试过 die();在策略方法中但没有起作用 我想要解决我的问题

laravel web authorization backend policy
1个回答
0
投票

我找到了解决方案,我刚刚删除了这个:

->can('view', 'thirdParty')

来自

api.php
并将其替换为

$this->authorize('view', ThirdParty::class);

在控制器操作中,它对我有用!

© www.soinside.com 2019 - 2024. All rights reserved.