Laravel middlware'only'为每条路线开火

时间:2015-11-29 17:13:13

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

无论我做什么,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]);
    }
}

1 个答案:

答案 0 :(得分:3)

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