Laravel - 为什么跳过中间件?
Laravel - Why middleware get skipped?
假设用户已经注销并且用户访问了这个页面http://domain.com/admin
在控制器中,我有这样的__construct
方法:
public function __construct() {
$this->middleware('auth');
dd("Hello World");
}
为什么在屏幕上显示"Hello World"? $this->middleware
应该首先执行并通过 auth 中间件重定向到登录页面,因为用户尚未登录。
但是,如果我像这样删除 dd("Hello World");
:
public function __construct() {
$this->middleware('auth');
}
它工作正常并重定向到登录页面。
因为 $this->middleware
方法实际上将您的控制器 methods/actions 绑定到您正在定义的 auth
中间件。它不会在此时执行,而是在您的路线被调用时执行。
参考: Laravel docs
it is more convenient to specify middleware within your controller's
constructor. Using the middleware method from your controller's
constructor, you may easily assign middleware to the controller's
action.
并且在走这条路线时:http://domain.com/admin
。实际上,控制器的 index
方法在控制器对象被实例化并绑定中间件后触发。
假设用户已经注销并且用户访问了这个页面http://domain.com/admin
在控制器中,我有这样的__construct
方法:
public function __construct() {
$this->middleware('auth');
dd("Hello World");
}
为什么在屏幕上显示"Hello World"? $this->middleware
应该首先执行并通过 auth 中间件重定向到登录页面,因为用户尚未登录。
但是,如果我像这样删除 dd("Hello World");
:
public function __construct() {
$this->middleware('auth');
}
它工作正常并重定向到登录页面。
因为 $this->middleware
方法实际上将您的控制器 methods/actions 绑定到您正在定义的 auth
中间件。它不会在此时执行,而是在您的路线被调用时执行。
参考: Laravel docs
it is more convenient to specify middleware within your controller's constructor. Using the middleware method from your controller's constructor, you may easily assign middleware to the controller's action.
并且在走这条路线时:http://domain.com/admin
。实际上,控制器的 index
方法在控制器对象被实例化并绑定中间件后触发。