How To Set A Session Variable Before Anything Loads In Laravel?

- 1 answer

I want to set a session based on the URL (like or 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());
    } else {
        Session::put('current_language', Language::where('short', strtoupper($url_array[0]))->get());

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



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


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