Alvin Bakker Alvin Bakker - 7 months ago 25
PHP Question

How to set a session variable before anything loads in Laravel?

I want to set a session based on the URL (like http://de.domain.com or http://es.domain.com) before anything in Laravel loads and thought to do this in the

ConfigServiceProvider
:

public function boot() {
// set language
$parse = parse_url(url());
$url_array = explode('.', $parse['host']);
if($url_array[0] == 'domain' || $url_array[0] == 'www') {
Session::put('current_language', Language::where('short', 'EN')->get());
App::setLocale('en');
} else {
Session::put('current_language', Language::where('short', strtoupper($url_array[0]))->get());
App::setLocale($url_array[0]);
}
}


But this is not working at all. Setting it in the
Routes
sets the session, but after pages are loaded and thus working on the next page, instead on the current one.

What's the best approach? Cause setting it in the
Routes
is surely not a good idea

Answer

You can't set a session variable in a service provider because in Laravel the session is initialized in this middleware:

\Illuminate\Session\Middleware\StartSession::class

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

So, the best approach would be to populate the session variable in a middleware, and let the middleware execute after Laravel StartSession middleware, so that the session would be accessible.

Setting the variable in a middleware should be good enough for you, as the Laravel's request cycle is:

Service Providers -> Middlewares -> Controllers -> Views 

So, setting the session in a middleware will let the variable be available in your controllers and views