Home > Mobile >  Confused about $this->authorize() in Laravel controller policies
Confused about $this->authorize() in Laravel controller policies

Time:05-25

public function update(Request $request, Post $post)
{
    $this->authorize('update', $post);

}

From my understanding, the second argument tells Laravel which Model is the 'update' permission about. In this case, $post (App\Models\Post) model. The confusing part for me is if the authorize() second exists only as a reference to the model or if does pass an Instance of the actual model, even if the 'update' method doesn't require it?

Example of update policy not requiring the actual $post instance:

public function update(User $user)
    {
        return $user->hasPermissionTo('update posts');
    }

Example of update policy requiring the $post instance:

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

Would $this->authorize('update', $post) work for both examples even if in one case the update method requires only one argument and in another it requires two? What if it required three?

CodePudding user response:

You are writing the policy methods, so you determine what parameters it needs. In your example you're calling $this->authorize('update', $post) so your policy method needs to have a $post parameter to represent the object being updated.

Obviously if you don't pass that as a parameter it has nothing to authorize against. Policy methods without a model parameter are meant for situations where there is no model to authorize, such as a creation function.

From the documentation:

Some policy methods only receive an instance of the currently authenticated user. This situation is most common when authorizing create actions. For example, if you are creating a blog, you may wish to determine if a user is authorized to create any posts at all. In these situations, your policy method should only expect to receive a user instance.

CodePudding user response:

public function update(User $user)
{
    return $user->hasPermissionTo('update posts');
}

this user can update all the post

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

this user can update only own post

CodePudding user response:

public function update(Request $request, Post $post)
{
    $this->authorize('update', $post);

}

'update' - authorizaton policy function name

$post - you are just passing data to that function, because user just automatically comes from Auth::user()

  • Related