英文:
How $this->authorize() understand which policy should be called in laravel?
问题
我有一些策略,如CoursePolicy
,PostPolicy
,CommentPolicy
,这些都在Laravel策略文件夹中定义。
此外,我还在AuthServiceProviderClass
的boot
方法中将所有策略注册到策略数组中。
但是Laravel如何知道在控制器类中编写时应该调用哪个策略类的方法(在这种情况下是view
方法)?
$this->authorize( 'view', Course::findOrFail( $course ) );
英文:
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 ) );
答案1
得分: 0
Sure, here is the translated content:
在进行policies时,对于每个model
,您需要创建一个相应的policy
来授权用户的操作(这些操作涉及查看、创建、更新和删除资源)。
在注册策略时,您需要告知Laravel在授权对特定model
类型的操作时使用哪个policy
。
如果您在使用Artisan控制台生成策略时使用了--model
选项(例如:php artisan make:policy CoursePolicy --model=Course
),它将已经包含viewAny
、view
、create
、update
、delete
、restore
和forceDelete
操作的方法。
您正在使用Controller Helpers$this->authorize()
,因此您需要在正确的方法上写入操作的名称,如果授权失败,它将返回一个403异常。
以下是控制器方法与策略方法的映射,以便您不要在不同的方法上命名其他策略。
控制器方法 | 策略方法 |
---|---|
index | viewAny |
show | view |
store | create |
create | create |
edit | update |
update | update |
destroy | delete |
英文:
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 |
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论