首页 文章

使用政策的Laravel Nova授权无效

提问于
浏览
0

我正在使用Laravel开发Web应用程序 . 我正在使用Nova进行管理面板 . 我现在正在做的是我使用文档中提到的策略来授权我的资源 . 但似乎它不起作用 . 这是我到目前为止所做的 . 我已经创建了这样的新星资源 .

class Item extends Resource
{
    /**
     * The model the resource corresponds to.
     *
     * @var string
     */
    public static $model = \App\Models\Item::class;

    /**
     * The single value that should be used to represent the resource when being displayed.
     *
     * @var string
     */
    public static $title = 'id';

    /**
     * The columns that should be searched.
     *
     * @var array
     */
    public static $search = [
        'id',
    ];

    /**
     * Get the fields displayed by the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function fields(Request $request)
    {
        return [
            ID::make()->sortable(),
        ];
    }

    /**
     * Get the cards available for the request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function cards(Request $request)
    {
        return [];
    }

    /**
     * Get the filters available for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function filters(Request $request)
    {
        return [];
    }

    /**
     * Get the lenses available for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function lenses(Request $request)
    {
        return [];
    }

    /**
     * Get the actions available for the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function actions(Request $request)
    {
        return [];
    }
}

然后我为该资源创建了一个名为Item的Laravel Model类 .

然后我创建了政策 .

class ItemPolicy
{
    use HandlesAuthorization;

    public function viewAny(User $user)
    {
        return true;
    }

    public function view(User $user, $item)
    {
        return true;
    }


    public function create(User $user)
    {
        return false;
    }

    public function update(User $user, $item)
    {

        return false;
    }

    public function delete(User $user, $item)
    {
        return false;
    }

    public function restore(User $user, $item)
    {
        return false;
    }

    public function forceDelete(User $user, $item)
    {
        return false;
    }
}

我在AuthServiceProvider中注册了该策略 .

protected $policies = [

    Item::class => ItemPolicy::class,
];

当我在nova管理面板中看到项目列表时,我仍然可以创建该项目 . 怎么了?应隐藏创建项目的选项 . 我的代码有什么问题,我该如何解决?

1 回答

  • 0

    也许是因为你在方法参数中缺少模型类型

    在传递$ item的所有方法中添加 Item $item ,如下所示:

    public function update(User $user, Item $item)
    {
        return false;
    }
    

    您也可以排除所有不可用的方法,默认情况下它们将被禁用

相关问题