問題描述
Laravel 中間件“僅”為每條路線觸發 (Laravel middlware 'only' fires for every route)
無論我做什麼 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:
Looking at Laravel code it seems that when you use:
$this‑>middleware('crud', ['only' => []]);
Laravel will always use this middleware (for all Controller methods) so you should not middleware with empty only
option.
So you should modify this contructor:
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]);
}
}
and in child controllers that extend from BaseController
you should do something like this in constructor:
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();
}
(by Sterling Duchess、Marcin Nabiałek)