I have a few policies like
CoursePolicy
,
PostPolicy
,
CommentPolicy
is defined in Laravel policy folder.
As well as I registered all the policies under the policy array in the boot method of AuthServiceProviderClass
.
But how does Laravel knows which policy class's method(in this case view method) should be called when writing in controller class!?
$this->authorize( 'view', Course::findOrFail( $course ) );
When doing policies, for each model
you do a corresponding policy
to authorize user actions (these actions are related to viewing, creating, updating, and deleting the resource).
When registering policies you inform Laravel which policy
to use when authorizing actions against a given model
type.
If you used the --model
option (ex: php artisan make:policy CoursePolicy --model=Course
) when generating your policy via the Artisan console, it will already contain methods for the viewAny
, view
, create
, update
, delete
, restore
, and forceDelete
actions.
You are using the Controller Helpers $this->authorize()
, so you need to write the name of the action on the correct method, and will return a exception with 403 if it fails.
This is the map for controller method<->policy method so you don't name other policy on different method.
Controller Method | Policy Method |
---|---|
index | viewAny |
show | view |
store | create |
create | create |
edit | update |
update | update |
destroy | delete |