7

I'm trying to share a Session value with all views using AppServiceProvider class.

In the boot() function I said: view()->share('key', Session::get('key'));

But, the value is null. What can be the problem? In the Controller I'm setting it, it works fine. Even after removing the Session::put() line, the value is still in the session (obviously).

Moppo
  • 18,797
  • 5
  • 65
  • 64
Martin Fejes
  • 677
  • 12
  • 20

1 Answers1

10

In Laravel session is initialized in a middleware that is handled by this class:

\Illuminate\Session\Middleware\StartSession::class

When the service providers are booted, this middleware has not been executed, because all the middlewares execute after the service providers boot phase

So, instead of sharing the variable from a service provider, you can create a middleware and share the session variable from there, or you can use a view composer with a callback in your service provider:

public function boot()
{
    view()->composer('*', function ($view) 
    {
        //this code will be executed when the view is composed, so session will be available
        $view->with('key', \Session::get('key') );    
    });  
}

This will work, as the callback will be called before the views are composed, when the middleware has already been executed, so session will be availabe

In general, pay attention at your middleware's execution order: if you want to access the session from a middleware, that should execute after Laravel's StartSession::class middleware

Moppo
  • 18,797
  • 5
  • 65
  • 64
  • Thank you. Although the answer is good and it works, there was a mistake in my approach. Wanting to show the value before the controller is too soon, because the value is only set later. On the first load it will be empty. Maybe a view composer will solve my problem. :) – Martin Fejes Nov 25 '15 at 13:37
  • 1
    Yes, if you set the variable in the controller, in the first call (before setting it) of the middleware it will be null. You could also enclose the statment in the middleware with a `if ( !is_null($var) ) { //share it }`, so in the first call you'll not share anything...don't know if it meets your app's needs – Moppo Nov 26 '15 at 08:36
  • 1
    Thanks, definitely useful info! :) – Martin Fejes Nov 27 '15 at 09:42