Laravel: How to access session value in AppServiceProvider?

Is access to session values ​​available in AppServiceProvider ? I would like to share the meaning of the session globally in all views.

+6
source share
2 answers

You cannot read the session directly from the service provider: in Laravel, the session is processed by StartSession middleware that runs after the service providers download phase

If you want to share the session variable with the entire view, you can use the 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 is displayed, so the StartSession will already be executed at this point

+9
source

Do the following steps for me on Laravel 5.2 lead to errors in your application?

AppServiceProvider.php

 class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { \Session::put('lang', 'en_US'); view()->share('lang', \Session::get('lang', 'de_DE')); } /** * Register any application services. * * @return void */ public function register() { // } } 

home.blade.php

 <h1>{{$lang}}</h1> 

Shows "en_US" in the browser.

0
source

All Articles