title: Laravel 5.4: how to pass model object to controller via middleware?
body: <p>I am creating an app in Laravel 5.4, where I have a middleware <code>ValidateBooking</code> and then a controller called with a URL like <code>/booking/6/car</code>, which lists all the cars assigned to that booking. </p>
  
  <p>In the <code>ValidateBooking</code> middleware I am validating the booking id <code>6</code> in the above URL by using the <code>Booking::find(6)</code> Eloquent function. But what I want is, if the Booking exists then pass that object to the controller, so I do not fetch it again in the controller. I don't want to query the database twice for the same thing.</p>
  
  <p>I tried a few methods to merge the model object with <code>$request</code> in the middleware, but was not able to access it in the controller properly. </p>
  
  <p>My middleware code is:</p>
  
  <pre><code>&lt;?php
  
  namespace App\Http\Middleware\Booking;
  
  use Closure;
  use App\Booking\Booking;
  
  class ValidateBooking
  {
      /**
       * Handle an incoming request.
       *
       * @param  \Illuminate\Http\Request  $request
       * @param  \Closure  $next
       * @return mixed
       */
      public function handle($request, Closure $next)
      {
          $booking = Booking::find($request-&gt;booking_id);
          if (!$booking) {
              return redirect(route('booking.show', $request-&gt;booking_id));
          }
          $request-&gt;attributes-&gt;add(['bookingInstance' =&gt; $booking]);
          return $next($request);
      }
  }
  </code></pre>
  
  <p>And then fetching it in the Controller like:</p>
  
  <p><code>$request-&gt;get('bookingInstance')</code></p>
  
  <p>It works if I pass any string value or something, but not for an object? Please advise what could be the best way for this.</p>