Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ashens's avatar

Change Session Cookie name at runtime

My Laravel app has multiple subdomains, which are their own isolated environments:

domain1.mywebsite.com
domain2.mywebsite.com  

However, the session cookie name is the same for both subdomains. I want the session cookie to be different for each subdomain.

The cookie name is defined in session.php

 'cookie' => env(
        'SESSION_COOKIE',
        Str::slug(env('APP_NAME', 'laravel'), '_') . '_session'
    ),

APP_NAME is used to uniquely create the cookie name, how can I change this at runtime to be different depending on what subdomain I'm on?

Doing

config(['session.cookie' => $subdomain]);

does not change the cookie name at runtime

0 likes
1 reply
yahoo30000's avatar

because you have to use a middleware for it and use $middlewarePriority to re-config cookie name before initializing cookies.

You can't change cookie's name after they are outputed to the respone headers. (Technically)

protected $middlewarePriority = [
        \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
        \Illuminate\Cookie\Middleware\EncryptCookies::class,
       
	    // Domain or SubDomain or Tenant Cookie Modifier Middleware Here

        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \Illuminate\Contracts\Auth\Middleware\AuthenticatesRequests::class,
        \Illuminate\Routing\Middleware\ThrottleRequests::class,
        \Illuminate\Routing\Middleware\ThrottleRequestsWithRedis::class,
        \Illuminate\Contracts\Session\Middleware\AuthenticatesSessions::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,

        // Spatie Team Middleware Here

        \Illuminate\Auth\Middleware\Authorize::class,
    ];

keep in mind that you should use that middleware somewhere to activate this priority. somewhere like routes vie $middlewareAliases or direct class names.

Good luck

1 like

Please or to participate in this conversation.