Laravel: How to access session value in AppServiceProvider?

10,678

You can't read session directly from a service provider: in Laravel the session is handled by StartSession middleware that executes after all the service providers boot phase

If you want to share a session variable with all view, you can use a view composer from your service provider:

public function boot()
{
    view()->composer('*', function ($view) 
    {
        $view->with('your_var', \Session::get('var') );    
    });  
}

The callback passed as the second argument to the composer will be called when the view will be rendered, so the StartSession will be already executed at that point

Share:
10,678
Qazi
Author by

Qazi

I am a hands-on, highly competent software engineer with 7+ years experience in designing architect of application, development and testing software across a variety of platforms. I have worked on numerous projects from concept to completion. A specialist in PHP and open source technologies, I take pride in coding to consistently high standards and regularly refresh my skills to ensure I keep up with ongoing developments.

Updated on June 15, 2022

Comments

  • Qazi
    Qazi almost 2 years

    Is there any way available to access Session values in AppServiceProvider? I would like to share session value globally in all views.

    • Moppo
      Moppo over 8 years
      please, check my updated answer
    • Qazi
      Qazi over 8 years
      @Moppo it works Thanks
  • Qazi
    Qazi over 8 years
    \session not working, getting empty results, eg i tried this print_r(\Session::all()); no results
  • Moppo
    Moppo over 8 years
    @Kaloyan: are you sure you are not setting the variable somewhere else? I don't think you can access the session from a service provider since it's started in a middleware
  • kalatabe
    kalatabe over 8 years
    @Moppo, yes, I'm not setting this anywhere else, maybe it's something that changed between 5.1 and 5.2?
  • Moppo
    Moppo over 8 years
    it seems that you can write session from a service provider, but you can't read it. In your case it works as you are reading the value you're setting directly on the same request. But if you remove the \Session::put('lang', 'en_US'); line and make another request, the value will not be read from the session
  • Shofiullah Babor
    Shofiullah Babor about 5 years
    Great It Work fine Thanks