简体   繁体   English

在Laravel 5.2中,auth() - > user()为null

[英]auth()->user() is null in Laravel 5.2

I just update the composer to Laravel 5.2 and not able to view password protected pages. 我只是将作曲家更新为Laravel 5.2并且无法查看受密码保护的页面。 Basically below line of code is not working. 基本上下面的代码行不起作用。

auth()->user() 

Can somebody suggest why this is not working ? 有人可以建议为什么这不起作用?

Make sure any routes that require sessions (which Auth uses) are behind the 'web' middleware group. 确保需要会话(Auth使用的)的所有路由都在“web”中间件组后面。

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

This is a change that is new to 5.2. 这是对5.2的新变化。 By default routes do not have this middleware stack applied. 默认情况下,路由没有应用此中间件堆栈。 The web middleware group sets the session store, cookies, and csrf protection. Web中间件组设置会话存储,cookie和csrf保护。

In Laravel 5.2 upgrade, routes that use Auth must be in web middleware group. 在Laravel 5.2升级中,使用Auth的路由必须位于Web中间件组中。

I solved this problem in app/Http/Kernel.php moving web middleware groups to global middlewares. 我在app / Http / Kernel.php中解决了这个问题,将Web中间件组移动到全局中间件。

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
];

May it will help someone else. 愿它能帮助别人。 But don't forget to see what the guard you are using. 但是别忘了看看你正在使用什么样的guard For example, for admins you may not default guard, but create your own. 例如,对于管理员,您可能不会默认保护,但创建自己的。 Don't forget it. 不要忘记它。 Calling \\Auth::guard($guard)->user() 调用\\Auth::guard($guard)->user()

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). 对于那些不想盲目地向路由添加中间件的人,您只需要将管理cookie和会话的类添加到相关的中间件组(在我的情况下为api )。 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: 这就是我的App\\Http\\Kernel::$middleWare变量最终看起来的App\\Http\\Kernel::$middleWare

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 使用Laravel 5.3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM