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,AppModelsPhoto'], ['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,AppModelsPhoto,request->parent'], ['only' => ['store']]);
But that won’t work. Thanks a lot if you can help me on this one!
Advertisement
Answer
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,AppModelsPhoto'], ['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 }