Issue
Is there any easy way of retrieving the route binded model within a Request?
I want to update a model, but before I do, I want to perform some permissions checks using the Requests authorize()
method. But I only want the owner of the model to be able to update it.
In the controller, I would simply do something like this:
public function update(Request $request, Booking $booking)
{
if($booking->owner->user_id === Auth::user()->user_id)
{
// Continue to update
}
}
But I'm looking to do this within the Request, rather than within the controller. If I do:
dd(Illuminate\Http\Request::all());
It only gives me the scalar form properties (such as _method
and so on, but not the model).
Question
If I bind a model to a route, how can I retrieve that model from within a Request?
Many thanks in advance.
Solution
Absolutely! It’s an approach I even use myself.
You can get the current route in the request, and then any parameters, like so:
class UpdateRequest extends Request
{
public function authorize()
{
// Get bound Booking model from route
$booking = $this->route('booking');
// Eager-load owner relation if it’s not loaded already
$booking->loadMissing('owner');
return (string) $booking->owner->user_id === (string) $this->user()->getKey();
}
}
Unlike smartman’s (now deleted) answer, this doesn’t incur another find query if you have already retrieved the model via route–model binding.
However, I’d also personally use a policy here instead of putting authorisation checks in form requests.
Answered By - Martin Bean
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.