Laravel 5 : passing a Model parameter to the middleware

3.8k views Asked by At

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)

3

There are 3 answers

0
peterm On BEST ANSWER

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.

0
bittids On

A more eloquent way of resolving this problem is to create a constructor method in the middleware, inject the model(s) as dependencies, pass them to class variables, and then utilize the class variables in the handle method.

For authority to validate my response, see app/Http/Middleware/Authenticate.php in a Laravel 5.1 installation.

For middleware MyMiddleware, model $myModel, of class MyModel, do as follows:

use App\MyModel;

class MyMiddleware
{
    protected $myModel;

    public function __construct(MyModel $myModel)
    {
        $this->myModel = $myModel;
    }

    public function handle($request, Closure $next)
    {
        $this->myModel->insert_model_method_here()
       // and write your code to manipulate the model methods

       return $next($request);
    }
}
0
Pooria Honarmand On

You don't need to pass the model to middleware, Because you already have access to model instance inside the middleware!
Lets say we have a route like this:

example.test/api/post/{post}

now in our middleware if we want to have access to that post dynamically we go like this

$post = $request->route()->parameter('post');

now we can use this $post, for example $post->id will give us the id of the post, or $post->replies will give us the replies belong to the post.