1
votes

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);
}
2
Please provide some code for us to review.Derek Pollard
Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example.Fabio Antunes
I'm using default laravel authentication approach, i dont know which part of code i should provide herealex
Are you using the default User model?user2094178
@user2094178 yes i am using default User modelalex

2 Answers

8
votes

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

0
votes

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