简体   繁体   English

Laravel 无法为用户模型创建策略

[英]Laravel can't create policy for user model

Can' create Policy for User model.无法为用户模型创建策略。

I created Policy like this我创建了这样的策略

php artisan make:policy UserPolicy --model=User

Got UserPolicy.php with CRUD actions.获得带有 CRUD 操作的 UserPolicy.php。

Then inside AuthServiceProvider.php I added然后在 AuthServiceProvider.php 我添加

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

But nothing happens.但什么也没有发生。 As I understand generated Policy for User model by default returning false on every action, I even explicitly added this to UserPolicy class:据我了解,默认情况下为用户模型生成的策略在每个操作上都返回 false,我什至将其明确添加到 UserPolicy 类中:

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

Still can create user.还可以创建用户。

Later I will need to check if the user trying to edit his own post or not.稍后我将需要检查用户是否尝试编辑自己的帖子。 Everything should be forbidden for non-admin users except editing own profile (model).除了编辑自己的配置文件(模型)之外,所有非管理员用户都应该被禁止。

I must be missing something obvious.我一定遗漏了一些明显的东西。

UPDATE:更新:

If I put如果我把

$this->authorize('create', $user);

In UsersController create method, it will invoke create method Policy, so it seams that something is wrong with在UsersController的create方法中,会调用create方法Policy,所以看出来有问题

...
use App\Policies\UserPolicy;
use App\User;
...

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

inside AuthServiceProvider.在 AuthServiceProvider 中。

You can write this code for User Policy您可以为用户策略编写此代码

in UserPolicy.php :在 UserPolicy.php 中:

public function update(User $user, User $model)
{
    return $user->id === $model->id;
}

For example by this code you can update just your own profile.例如,通过此代码,您可以仅更新您自己的个人资料。

您需要将其放入控制器$this->authorize('create',$user)函数中

在您的控制器函数 $this->authorizeForUser($currentUser,'create', User::class) 中放入以下几行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM