【问题标题】:Laravel middlware 'only' fires for every routeLaravel 中间件“仅”为每条路由触发
【发布时间】:2016-03-03 07:39:19
【问题描述】:

无论我做什么 crud middlware 总是被解雇。但是,只有在声明了 $crud 数组并且仅针对它包含的路由时才应该触发它。但是,并非每次都会触发。即使我说$crud = []; 但是如果我声明['only' => ['route1', 'route2']] 那么它会按预期工作。

<?php

class BaseController extends Controller
{
    /**
     * Routes which DO NOT load users notifications.
     * @var Array Routes without notifications.
     */
    public $notifications;
    /**
     * Routes which DONT require users account to be configured.
     * @var Array Routes needing configuration.
     */
    public $configured;
    /**
     * Routes which REQUIRE ownership of resource.
     * @var Array CRUD routes.
     */
    public $crud;

    public function __construct()
    {
        $this->middleware('auth', ['except' => $this->routes]);
        $this->middleware('configured', ['except' => $this->configured]);
        $this->middleware('notifications', ['except' => $this->notifications]);
        $this->middleware('crud', ['only' => $this->crud]);
    }
}

【问题讨论】:

  • 提供更多信息。因为在我看来,除了定义的路由之外,“except”确实会触发。这是预期的。如果我理解错了,请进一步解释。

标签: php laravel laravel-5 laravel-routing laravel-middleware


【解决方案1】:

查看 Laravel 代码似乎是当你使用时:

$this->middleware('crud', ['only' => []]);

Laravel 将始终使用此中间件(适用于所有 Controller 方法),因此您不应使用空的 only 选项的中间件。

所以你应该修改这个构造函数:

public function __construct()
{
    $this->middleware('auth', ['except' => $this->routes]);
    $this->middleware('configured', ['except' => $this->configured]);
    $this->middleware('notifications', ['except' => $this->notifications]);
    if ($this->crud) {
        $this->middleware('crud', ['only' => $this->crud]);
    }
}

在从BaseController 扩展的子控制器中,您应该在构造函数中执行以下操作:

public function __construct() {
   // here you set values for properties
   $this->routes = ['a','b'];
   $this->configured = ['c'];
   $this->notifications = ['d'];
   $this->crud = ['e','f'];

   // here you run parent contructor
   parent::__construct();
}

【讨论】:

  • 对于空数组使用'only'我也有同样的想法,但直到现在我找不到处理中间件选项的位置。能否提供相应源代码的链接?
  • @shock_gone_wild 查看Illuminate\Routing\ControllerDispatcher - 方法getMiddlewaremethodExcludedByOptions
  • 谢谢!你的答案绝对是正确的。 (我已经+1了)。但是我认为,实施的行为不是最佳的。在 Illuminate 源代码中! empty($options['only']) 应该替换为 ! isset(...) 在我的意见中“仅在“无”(空数组)上应用该中间件应该是有效的,并且根本不会触发该中间件
  • @shock_gone_wild 我看了看,你是对的。必须是 isset 但也必须是空的,只需要跳过空的和非实例化的。昨天我做了一些测试并在 laravel 框架 github 中提出了拉取请求,它被合并了,所以它现在应该在最新版本中更新。
  • @SterlingDuchess 我打算在空闲时间做同样的事情:)
猜你喜欢
  • 1970-01-01
  • 2020-08-23
  • 2016-02-27
  • 2012-11-06
  • 2016-06-03
  • 2020-07-30
  • 1970-01-01
  • 2015-08-28
  • 2016-12-09
相关资源
最近更新 更多