Laravel – How to get current user in AppServiceProvider

Laravel session is initialized in a middleware so you can’t access the session from a Service Provider, because they execute before the middleware in the request lifecycle

You should use a middleware to share your varibles from the session

However, If for some other reason you want to do it in a service provider, you can do it using a view composer with a callback, like this:

public function boot()
{
    //compose all the views....
    view()->composer('*', function ($view) 
    {
        $cart = Cart::where('user_id', Auth::user()->id);
        
        //...with this variable
        $view->with('cart', $cart );    
    });  
}

The callback will be executed only when the view is actually being composed, so middlewares will be already executed and session will be available

Leave a Comment