Laravel Policies - How to Pass Multiple Arguments to function

后端 未结 1 1980
天命终不由人
天命终不由人 2020-12-24 03:30

I\'m trying to authorize a users character to delete/update post. I was using policies to do so, but I could only pass one parameter to the policy function. If I pass more t

相关标签:
1条回答
  • 2020-12-24 03:31

    I think there is possibly some confusion here on what functions are doing what.

    When you use

    Gate::define('delete-comment', function ($user, $post, $comment) {
        //
    });
    

    Or in the CommentPolicy

    public function delete(User $user, Post $post, Comment $comment)
    {
        return $user->id === $post->user_id;
    }
    

    All you are doing is defining the rules. At this point, we aren't worried about passing anything, only that the objects we received can or should be able to interact with each other. The only difference between these two is when using policies, it's just an easy way to abstract all your rules into one simple and easy to read class. If you have an app with potentially hundreds of tables and models, it will get confusing fast if you have these rules littered all over your app so policies would help to keep them all organized.

    It's when you are actually checking if someone has permission to do something when you should be passing these items along. For example, when you do the following,

    if (Gate::allows('delete-comment', [$post, $comment])) {
        // 
    }
    

    Or if in the CommentController

    $this->authorize('delete', [$post, $comment]);
    

    That is what controls which parameters are going to be passed to the policy or the Gate::define method. According to the docs, the $user parameter is already added for you so in this case, you only need to worry about passing the correct $post and $comment being modified.

    0 讨论(0)
提交回复
热议问题