Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel retrieve binded model in Request

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.

like image 848
Phil Cross Avatar asked Apr 21 '15 14:04

Phil Cross


2 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()     {         // 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.

like image 134
Martin Bean Avatar answered Sep 23 '22 07:09

Martin Bean


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!

like image 35
godbout Avatar answered Sep 22 '22 07:09

godbout