alex February 2016

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);
}

Answers


Moppo February 2016

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

Post Status

Asked in February 2016
Viewed 2,962 times
Voted 5
Answered 1 times

Search




Leave an answer