phplaravellaravel-formrequest

Laravel: retrieve bound model from request


Is there any easy way of retrieving the route's bound model within a FormRequest class?

I want to update a model, but before I do, I want to perform some permissions checks using the FormRequest::authorize() method.

In the controller, I would simply use the bound parameter $booking:

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 FormRequest, rather than within the controller. If I use $this->all() it only gives me the form inputs (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?


Solution

  • 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');
    
            // Check owner is the currently authenticated user
            return $booking->owner->is($this->user());
        }
    }
    

    Because you have already retrieved the model via route–model binding, this doesn’t incur another find query.


    As a note, I’d also personally use a policy here instead of putting authorisation checks in form requests.