【问题标题】:Laravel 5 : passing a Model parameter to the middlewareLaravel 5:将模型参数传递给中间件
【发布时间】:2015-06-13 17:48:34
【问题描述】:

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

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

你会如何在 Controller 的构造函数中传递它?这不起作用:

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

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

【问题讨论】:

    标签: laravel laravel-5 middleware


    【解决方案1】:

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

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

    在您的中间件中:

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

    通过这种方法,您可以将所需的任何模型传递给中间件。

    【讨论】:

      【解决方案2】:

      解决这个问题的一个更有说服力的方法是在中间件中创建一个构造方法,将模型作为依赖注入,将它们传递给类变量,然后在句柄方法中使用类变量。

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

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

      【讨论】:

        【解决方案3】:

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

        example.test/api/post/{post}
        

        现在在我们的中间件中,如果我们想动态访问该帖子,我们可以这样

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-08-30
          • 2013-12-20
          • 1970-01-01
          • 2017-01-12
          • 2018-10-08
          • 2013-02-04
          • 2015-10-19
          相关资源
          最近更新 更多