Laravel 5 : 将模型参数传递给中间件

Laravel 5 : passing a Model parameter to the middleware

我想将模型参数传递给中间件。根据这个 link (laravel 5 middleware parameters) ,我可以像这样在 handle() 函数中包含一个额外的参数:

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

你将如何在控制器的构造函数中传递它?这不起作用:

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

**注意:**重要的是我可以传递不同的模型(例如 ModelX、ModelY、ModelZ)

首先确保您使用的是 Laravel 5.1。中间件参数在以前的版本中不可用。

现在我不相信你可以将实例化对象作为参数传递给你的中间件,但是(如果你真的需要这个)你可以传递模型的 class 名称,即主键,如果你需要的话具体实例。

在你的中间件中:

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.

更 eloquent 解决这个问题的方法是在中间件中创建构造方法,将模型作为依赖项注入,将它们传递给 class 变量,然后利用class handle 方法中的变量。

有关验证我的回复的权限,请参阅 app/Http/Middleware/Authenticate。php 在 Laravel 5.1 安装中。

对于 class MyModel 的中间件 MyMiddleware,模型 $myModel,请执行以下操作:

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

您不需要将模型传递给中间件,因为您已经可以访问中间件内部的模型实例!
假设我们有这样一条路线:

example.test/api/post/{post}

现在在我们的中间件中,如果我们想动态地访问那个 post,我们会像这样

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

现在我们可以使用这个 $post,例如 $post->id 会给我们 post 的 ID,或者 $post->replies 会给我们回复属于post。