Search code examples
laravellaravel-5middleware

Laravel 5 : passing a Model parameter to the middleware


I would like to pass a model parameter to a middleware. According to this link (laravel 5 middleware parameters) , I can just include an extra parameter in the handle() function like so :

 public function handle($request, Closure $next, $model)
 {
   //perform actions
 }

How would you pass it in the constructor of the Controller? This isn't working :

public function __construct(){
    $model = new Model();
    $this->middleware('myCustomMW', $model);
}

**NOTE : ** it is important that I could pass different Models (ex. ModelX, ModelY, ModelZ)


Solution

  • First of all make sure that you're using Laravel 5.1. Middleware parameters weren't available in prior versions.

    Now I don't believe you can pass an instantiated object as a parameter to your middleware, but (if you really need this) you can pass a model's class name and i.e. primary key if you need a specific instance.

    In your middleware:

    public function handle($request, Closure $next, $model, $id)
    {
        // Instantiate the model off of IoC and find a specific one by id
        $model = app($model)->find($id);
        // Do whatever you need with your model
    
        return $next($request);
    }
    

    In your controller:

    use App\User;
    
    public function __construct()
    {
        $id = 1; 
        // Use middleware and pass a model's class name and an id
        $this->middleware('myCustomMW:'.User::class.",$id"); 
    }
    

    With this approach you can pass whatever models you want to your middleware.