Laravel 5 : passing a Model parameter to the middleware

此生再无相见时 提交于 2020-03-23 04:28:09

问题


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)


回答1:


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.




回答2:


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);
    }
}



回答3:


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.


来源:https://stackoverflow.com/questions/30821733/laravel-5-passing-a-model-parameter-to-the-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!