Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: How to access session value in AppServiceProvider?

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

like image 374
Qazi Avatar asked Feb 10 '16 11:02

Qazi


1 Answers

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

like image 200
Moppo Avatar answered Sep 28 '22 04:09

Moppo