我正在使用laravel 6并在我的应用中有2条路线; 索引和仪表板。我的routes/web
是:
Auth::routes();
Route::middleware(['auth'])->group(function () {
Route::get('/index', 'todoApp\TodoController@index')->name('index');
Route::get('/dashboard', 'todoApp\Dashboard@dashboard')->name('dashboard');
});
我最近添加了仪表板路线。Auth::user()
当我将其转储到仪表板路由中但不包含在索引中时为null。那是什么
在中间件堆栈运行之前,实例化了您的控制器;这就是Laravel如何知道您通过构造函数设置了什么中间件的方法。因此,您此时将无法访问已验证的用户或会话。例如:
public function __construct()
{
$this->user = Auth::user(); // will always be null
}
如果您需要分配此类变量或访问此类信息,则需要使用控制器中间件,该中间件将在StartSession
中间件之后的堆栈中运行:
public function __construct()
{
$this->middleware(function ($request, $next) {
// this is getting executed later after the other middleware has ran
$this->user = Auth::user();
return $next($request);
});
}
dashboard
调用该方法时,中间件堆栈已将请求一直传递到堆栈的末尾,因此Auth
在该位置运行并可用的所有中间件都已经在运行,这就是为什么您可以访问该中间件Auth::user()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句