我有一个 Controller 父类,它接受中间件添加到 $request
的一些属性,并使它们对所有子类可用。
所以在我的中间件 handle()
函数中我有:
$request->attributes->add(['project' => $project]);
在我的 Controller 中 __construct()
我有:
$this->project = $request->attributes->get('project');
这在 5.2 中运行良好,但自升级到 5.3 后,我意识到 Controller __construct()
在我的中间件 handle()
函数之前被调用,并且所以 'project' 属性为 null
。
有谁知道为什么在 Controller 之后调用中间件? 从 5.2 到 5.3 有什么变化吗?
谢谢!
最佳答案
看起来这是在 5.3 中发生的变化:
https://laravel-news.com/2016/08/controller-construct-session-changes-in-laravel-5-3/
所以现在你可以像这样在 Controller 构造函数中调用中间件:
$this->middleware(function ($request, $next) {
$this->request = $request;
$this->project = $request->attributes->get('project');
return $next($request);
});
因为 Controller 中间件最后会被调用,这样你就可以在路由中间件设置好之后访问类中的请求属性。
干杯。
关于laravel-5.3 - Laravel 5.3 Controller __construct 在中间件之前调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39534947/