Martin Fejes Martin Fejes - 4 months ago 61x
PHP Question

Laravel - Session variable is null in Service Provider

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


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

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


That is due to the fact that in Laravel session is initialized in a middleware that is handled by this 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) 
        $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