auth()->user() 在 Laravel 5.2 中为 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34504046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
auth()->user() is null in Laravel 5.2
提问by Yilmazerhakan
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.
我只是将 Composer 更新到 Laravel 5.2 并且无法查看受密码保护的页面。基本上下面的代码行不起作用。
auth()->user()
Can somebody suggest why this is not working ?
有人可以建议为什么这不起作用吗?
回答by lagbox
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. By default routes do not have this middleware stack applied. The web middleware group sets the session store, cookies, and csrf protection.
这是 5.2 的新变化。默认路由没有应用这个中间件堆栈。Web 中间件组设置会话存储、cookie 和 csrf 保护。
回答by Yilmazerhakan
In Laravel 5.2 upgrade, routes that use Authmust be in web middleware group.
在 Laravel 5.2 升级中,使用Auth 的路由必须在 web 中间件组中。
I solved this problem in app/Http/Kernel.phpmoving webmiddleware groups to globalmiddlewares.
我在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
];
回答by Илья Савич
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()
愿它会帮助别人。但不要忘记看看guard
你正在使用什么。例如,对于管理员,您可能不会默认守卫,而是创建自己的守卫。不要忘记它。打电话\Auth::guard($guard)->user()
回答by Precastic
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:
对于那些不想盲目地向路由添加中间件的人,您只需要将管理 cookie 和会话的类添加到相关的中间件组(api
在我的例子中)。对我来说,那些课程:
\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
变量最终的样子:
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