Auth::user() 在新路线中为空

Auth::user() is null in new route

我正在使用 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() 当我将它转储到仪表板路由但不在索引中时为空。什么是

我认为这与 'web' 中间件有关。如果您查看 Kernel.php(在 app\Http 中),您会发现网络中间件组。

这将向您展示它实际上调用了一个名为 StartSession 的中间件。根据您的路由文件(其中 web 不作为中间件包含在内)我认为您在控制器中没有会话并且无法访问它。

我不太明白为什么这只发生在您的 /dashboard 路由中,因为问题也应该在您的 /index 路由中(除非您在 TodoController 的某处添加了网络中间件)。

我认为这应该可以解决问题:

Route::middleware(['web', 'auth'])->group(function () {
    Route::get('/index', 'todoApp\TodoController@index')->name('index');
    Route::get('/dashboard', 'todoApp\Dashboard@dashboard')->name('dashboard');
});

如果你触发 php artisan make:auth 命令。 在哪里定义并不重要,因为它只定义 auth 路由

Route::middleware(['auth'])->group(function () {
    Route::get('/index', 'todoApp\TodoController@index')->name('index');
    Route::get('/dashboard', 'todoApp\Dashboard@dashboard')->name('dashboard');
});
Auth::routes();

你的Controller在中间件栈有运行之前被实例化;这就是 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 方法时,中间件堆栈已经将 Request 一直传递到堆栈的末尾,因此 Auth 所需的所有中间件都可以正常运行和可用那时已经 运行 这就是为什么你可以在那里访问 Auth::user()