Reputation: 4128
I can't create a Policy for the User model.
I created Policy like this:
php artisan make:policy UserPolicy --model=User
I got the 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, the generated Policy for User model by default returns false on every action, I even explicitly added this to UserPolicy
class:
public function create(User $user)
{
return false;
}
I still can create a 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
.
Upvotes: 6
Views: 4051
Reputation: 157
Put these lines in your controller function
$this->authorizeForUser($currentUser,'create', User::class)
Upvotes: 1
Reputation: 1353
You need to put this in you function in controller:
$this->authorize('create', $user);
Upvotes: 1
Reputation: 61
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.
Upvotes: 6