In Laravel,$this->authorize() 如何确定应调用哪个策略?

huangapple go评论61阅读模式
英文:

How $this->authorize() understand which policy should be called in laravel?

问题

我有一些策略,如CoursePolicyPostPolicyCommentPolicy,这些都在Laravel策略文件夹中定义。

此外,我还在AuthServiceProviderClassboot方法中将所有策略注册到策略数组中。

但是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),它将已经包含viewAnyviewcreateupdatedeleterestoreforceDelete操作的方法。

您正在使用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

huangapple
  • 本文由 发表于 2023年5月8日 02:09:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76195535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定