Home » Php » php – Laravel retrieve binded model in Request

php – Laravel retrieve binded model in Request

Posted by: admin April 23, 2020 Leave a comment

Questions:

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.

How to&Answers:

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()
    {
        $booking = $this->route('booking');

        return $booking->owner->user_id == $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.

Answer:

Once you did your explicit binding (https://laravel.com/docs/5.5/routing#route-model-binding) you actually can get your model directly with $this.

class UpdateRequest extends Request
{
    public function authorize()
    {
        return $this->booking->owner->user_id == $this->booking->user()->id;
    }
}

Even cleaner!

Answer:

To add on to Martin Bean‘s answer, you can access the bound instance using just route($param):

class UpdateRequest extends Request
{
    public function authorize()
    {
        $booking = $this->route('booking');

        return $booking->owner->user_id == $this->user()->id;
    }
}

Note: This works in Laravel 5.1. I have not tested this on older versions.