简体   繁体   中英

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). 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.

In Laravel the session is initialized via middleware , and all the middlewares execute after the service providers boot phase

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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