Laravel 5.4: how to pass model object to controller via middleware?

Viewed 5026

I am creating an app in Laravel 5.4, where I have a middleware ValidateBooking and then a controller called with a URL like /booking/6/car, which lists all the cars assigned to that booking.

In the ValidateBooking middleware I am validating the booking id 6 in the above URL by using the Booking::find(6) 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.

I tried a few methods to merge the model object with $request in the middleware, but was not able to access it in the controller properly.

My middleware code is:

<?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->booking_id);
        if (!$booking) {
            return redirect(route('booking.show', $request->booking_id));
        }
        $request->attributes->add(['bookingInstance' => $booking]);
        return $next($request);
    }
}

And then fetching it in the Controller like:

$request->get('bookingInstance')

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.

3 Answers
Related