5
votes

Can' create Policy for User model.

I created Policy like this

php artisan make:policy UserPolicy --model=User

Got UserPolicy.php with CRUD actions.

Then inside AuthServiceProvider.php I added

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:

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

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

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

inside AuthServiceProvider.

3
Yeah, on the docs laravel.com/docs/5.8/authorization look up Methods Without Models. It mentions a few times that there is additional steps to take, usually when using createN Mahurin

3 Answers

6
votes

You can write this code for User Policy

in 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.

0
votes

You need to put this in you function in controller $this->authorize('create',$user)

0
votes

Put below lines in your controller function $this->authorizeForUser($currentUser,'create', User::class)