Reputation: 7895
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);
}
Upvotes: 1
Views: 1627
Reputation: 19285
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
Upvotes: 10
Reputation: 1
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
Upvotes: 0