【问题标题】:Auth::user() is null in new routeAuth::user() 在新路由中为空
【发布时间】:2020-02-27 20:07:14
【问题描述】:

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

【问题讨论】:

  • 您在 Dashboard Controller 中将 Auth::user() 称为哪里??
  • __constructdashboard 方法中
  • 写入你的控制器。公共函数 __construct() { $this->middleware('auth'); }

标签: laravel authentication laravel-routing


【解决方案1】:

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

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

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

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

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

【讨论】:

【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    您的控制器在中间件堆栈运行之前被实例化;这就是 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()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-29
      • 2016-04-02
      • 1970-01-01
      • 2016-05-23
      • 2018-08-11
      • 2021-07-29
      • 2016-07-08
      • 1970-01-01
      相关资源
      最近更新 更多