Reputation: 65
so I made a policy and whatever I do the Web page returns 403. im very new to laravel so most likely im missing something :)
I made a model by
php artisan make:model exercise
| (I know I'm supposed to capitalize models but it was a typo)
Controller:
php artisan make:controller ExercisesController
Policy:
php artisan make:policy ExercisePolicy -m exercise
I registered policy in AuthServiceProvider.php (Also tried as 'App\Models\exercise'=>'App\Policies\ExercisePolicy'):
protected $policies = [
// 'App\Models\Model' => 'App\Policies\ModelPolicy',
exercise::class => ExercisePolicy::class,
];
In ExercisesController.php this is the function in which I use authentication:
public function create(\App\Models\User $user)
{
$this->authorize('create', $user);
return view('exercises/create');
}
And in policy this is how my create function looks like
public function create(User $user)
{
return $user->admin == true;
}
The route:
Route::get('/exercises/create', [App\Http\Controllers\ExercisesController::class, 'create']);
I tried putting die("Policy is called); and trying to just return true from the policy create function to check if it gets to that but it still returned 403 , at this point I'm pretty sure that the policy itself is not being called as it also returns 403 on default
If anyone could help thanks in advance!
Upvotes: 5
Views: 4719
Reputation: 212
I had this same issue and what I learnt was that Policies would work only on authenticated route.
Make sure your request is authenticated while implementing policies.
Upvotes: 2
Reputation: 50481
The call to authorize
is using the second argument to figure out what Policy to use. Since the second argument is $user
it would be looking for a Policy for the User model which you have not defined. To use the Policy for the exercise
model you would have to pass the class name so it would know what Policy to use:
$this->authorize('create', exercise::class);
Though you should correct your typo and rename the exercise.php
file to Exercise.php
and the classname to Exercise
.
Laravel 8.x Docs - Authorization - Writing Policies - Methods without Models
Upvotes: 7