Laravel 5:将Model参数传递给中间件 [英] Laravel 5 : passing a Model parameter to the middleware
问题描述
我想将模型参数传递给中间件.根据此链接(laravel 5个中间件参数),我可以添加一个额外的handle()
函数中的参数,如下所示:
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);
}
**注意:**重要的是,我可以传递不同的模型(例如ModelX,ModelY,ModelZ)
**NOTE : ** it is important that I could pass different Models (ex. ModelX, ModelY, ModelZ)
推荐答案
首先请确保您使用的是Laravel 5.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.
在您的中间件中:
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);
}
在您的控制器中:
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.
这篇关于Laravel 5:将Model参数传递给中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!