Laravel registerPolicies始终会获得“此操作未经授权". [英] Laravel registerPolicies always get "This action is unauthorized."

查看:211
本文介绍了Laravel registerPolicies始终会获得“此操作未经授权".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在laravel 5.5中,我创建了策略

In laravel 5.5 I create the policy

public function view()
{
    return true;
}

并将其注册到AuthServiceProvider

protected $policies = [
    // 'App\Model' => 'App\Policies\ModelPolicy',
    Post::class => PostPolicy::class,
];

在控制器中,我使用如下策略:

In the controller I use the policy like this:

$this->authorize('view');

无论函数view()返回true还是false,我都会收到错误This action is unauthorized.

I get the error This action is unauthorized whether the function view() returns true or false.

推荐答案

您的政策已注册为Post模型.

Your policy is registered for the Post model.

我假设您的view()方法在PostPolicy类内部.好像您要在没有模型实例的情况下使用它一样.

I assume your view() method is inside the PostPolicy class. It appears as if you'd want to use it without a model instance.

如果策略代码不需要模型实例,请使用$this->authorize('view', Post:class);.

Use $this->authorize('view', Post:class); if the policy code does not require a model instance.

您的视图方法还应该接收用户模型.

Your view method should furthermore receive a user model.

public function view(User $user) { ... };

否则,您想向谁检查权限.

Otherwise, for whom would you want to check permissions.

这篇关于Laravel registerPolicies始终会获得“此操作未经授权".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆