[英]laravel 5.1: Auth::check return false in ServiceProvider
I already looking for similar issues but didn't help me.我已经在寻找类似的问题,但没有帮助我。
Auth::check
always return false , Auth::guest
always return true, auth middleware work correct(lets request to continue if user is logged in and redirect user to login page if user is not logged in). Auth::check
总是返回 false , Auth::guest
总是返回 true, auth 中间件工作正确(如果用户登录,则请求继续,如果用户未登录,则将用户重定向到登录页面)。 whats wrong?怎么了?
EDIT: I understood it occurs in provider boot method , so the question would be : how to check user login status in a provider boot method?编辑:我知道它发生在提供者引导方法中,所以问题是:如何在提供者引导方法中检查用户登录状态? this is my provider boot method that share a menu in all views:
这是我的提供程序启动方法,它在所有视图中共享一个菜单:
public function boot(MenuController $menu_controller)
{
//dd(\Auth::check()) DOES NOT WORK HERE
$nav_menu = $menu_controller::roots()->get();
view()->share('nav_menu',$menus);
}
Auth::check()
is using session to check if a User
is autheticated. Auth::check()
使用会话来检查User
是否经过身份Auth::check()
。
In Laravel the session is initialized via middleware , and all the middlewares execute after the service providers boot phase在 Laravel 中,会话通过中间件初始化,所有中间件在服务提供者启动阶段之后执行
So, in your service provider you can't access the session: it has not been initialized yet因此,在您的服务提供商中,您无法访问会话:它还没有被初始化
The solution would be to check for authentication and do your work in a middleware, and let this middleware execute after this:解决方案是检查身份验证并在中间件中完成您的工作,然后让该中间件在此之后执行:
\Illuminate\Session\Middleware\StartSession::class
That is the middelware that starts the session.那是启动会话的中间件。
Another solution would be to use a callback with a view composer in the service provider:另一种解决方案是在服务提供者中使用带有视图编辑器的回调:
public function boot()
{
//compose all the views....
view()->composer('*', function ($view)
{
//works here
$check = \Auth::check();
//other code...
});
}
The callback will be executed only when the view is actually being composed, so middlewares will be already executed and session will be available只有在实际组合视图时才会执行回调,因此中间件将已经执行并且会话将可用
i have the same issue, and i solved it我有同样的问题,我解决了
here's how i solved it in my service provider `这是我在我的服务提供商处解决它的方法`
public function boot()
{
view()->composer('partial.navbar', function($view) {
$view->with('variabelToNavbar', $this->getVariable());
});
}
private function getVariable()
{
if(\Auth::check()) {
//some code u want
}
}
'
so the trick is to check auth with the function inside servide provider.. its not neat but it work for me所以诀窍是使用服务提供者内部的功能检查身份验证......它不整洁但对我有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.