auth()->user() is null in Laravel 5.2

眉间皱痕 提交于 2019-12-19 03:26:07

问题


I just update the composer to Laravel 5.2 and not able to view password protected pages. Basically below line of code is not working.

auth()->user() 

Can somebody suggest why this is not working ?


回答1:


Make sure any routes that require sessions (which Auth uses) are behind the 'web' middleware group.

Route::group(['middleware' => 'web'], function () {
    // your routes
});

This is a change that is new to 5.2. By default routes do not have this middleware stack applied. The web middleware group sets the session store, cookies, and csrf protection.




回答2:


In Laravel 5.2 upgrade, routes that use Auth must be in web middleware group.

I solved this problem in app/Http/Kernel.php moving web middleware groups to global middlewares.

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class
];



回答3:


May it will help someone else. But don't forget to see what the guard you are using. For example, for admins you may not default guard, but create your own. Don't forget it. Calling \Auth::guard($guard)->user()




回答4:


For those who don't want to blindly add middleware to routes, you simply need to add the classes that manage cookies & sessions to the relevant middleware group (api in my case). For me those classes where:

\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Session\Middleware\StartSession::class,

This is how my App\Http\Kernel::$middleWare variable ended up looking:

protected $middlewareGroups = [
    'web' => [
        ...
    ],

    'api' => [
        'throttle:60,1',
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Illuminate\Auth\Middleware\Authenticate::class
    ],
];

Using Laravel 5.3



来源:https://stackoverflow.com/questions/34504046/auth-user-is-null-in-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!