PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 12, 2022

[FIXED] Get request for the policies in controller constructor

 February 12, 2022     laravel, php     No comments   

Issue

I'm setting up policies for my laravel application, and I'm stuck with a problem. I have to put the policy in the constructor of my controller this way:

 public function __construct()
    {
        $this->middleware(['can:viewAny,App\Models\Photo'], ['only' => ['index']]);
        $this->middleware(['can:view,photo'], ['only' => ['show']]);
    }

Problem is, for the store action, I have to check one of the params sent in the request to check if the user is allowed to post on the related parent. According to the documentation, I could make my Policy this way:

public function store(User $user, int $parentId)
{
    $parent = Parent::find($parentId);
    return $user->id === $parent->user_id
}

And in the controller:

public function store(Request $request)
{
    $this->authorize('store', [$request->parent]);
    // The current user can store the photo...
}

But in the example, the authorization is put in the function, and there are no example with the usage of the request when treating the policy as a middleware. Is it even possible? I would have crafted something like:

    $this->middleware(['can:store,App\Models\Photo,request->parent'], ['only' => ['store']]);

But that won't work. Thanks a lot if you can help me on this one!


Solution

I found how to do it, I forgot about the request() helper. Thus, I can access everything put in the request, and I can call the helper directly inside the policy.

So I can do this in the contructor:

    $this->middleware(['can:store,App\Models\Photo'], ['only' => ['store']]);

And in the PhotoPolicy:

public function store(User $user)
{
    $input = request()->input();
    $parent = Parent::find($input['parent_id']);
    return $user->id === $parent->user_id
}


Answered By - Lyzvaleska
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing