Auth :: user()在新路由中为null [英] Auth::user() is null in new route

查看:87
本文介绍了Auth :: user()在新路由中为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用laravel 6,并且在我的应用中有2条路线;索引和仪表板. 我的routes/web是:

i'm using laravel 6 and have 2 route in my app; index and dashboard. My routes/web is:

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时我将其转储到仪表板路由中但未包含在索引中.什么是

i added dashboard route recently. Auth::user() is null when i dump it in dashboard route but doesn't in index. What's the

推荐答案

在中间件堆栈运行之前,您的控制器已实例化.这就是Laravel如何知道您通过构造函数设置了什么中间件的方法.因此,您此时将无法访问经过身份验证的用户或会话.例如:

Your Controller is instantiated before the middleware stack has ran; this is how Laravel can know what middleware you have set via the constructor. Because of this you will not have access to the authenticated user or sessions at this point. Ex:

public function __construct()
{
    $this->user = Auth::user(); // will always be null
}

如果您需要分配此类变量或访问此类信息,则需要使用控制器中间件,该控制器中间件将在StartSession中间件之后运行:

If you need to assign such a variable or access this type of information you would need to use a controller middleware which will run in the stack after the StartSession middleware:

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()的原因.

When the dashboard method is called, the middleware stack has already passed the Request all the way through to the end of the stack so all the middleware needed for Auth to be functioning and available has already ran at that point which is why you have access to Auth::user() there.

这篇关于Auth :: user()在新路由中为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆