Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel can't create policy for user model

Tags:

php

laravel

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.

like image 948
RomkaLTU Avatar asked Jul 05 '19 17:07

RomkaLTU


2 Answers

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.

like image 52
Masoud Avatar answered Sep 19 '22 21:09

Masoud


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

like image 42
Mohammed Aktaa Avatar answered Sep 22 '22 21:09

Mohammed Aktaa