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

martinszeltins's avatar

How to have multiple domains for COOKIE session?

My application can be accessed using 2 different domain names www.4evergaming.com and www.best4games.com

Here is how my routes file looks like

Route::pattern('domain', '(www.4evergaming.com|www.best4games.com)');
Route::domain('{domain}')->group(function ()
{
	// Routes here...
})

But in my config/session.php I can only have one domain...

'domain' => '.4evergaming.com',

I need to set session cookies for both domains but how can I do this?

0 likes
4 replies
Tippin's avatar
Tippin
Best Answer
Level 13

@martinzeltin What I did to solve this was create a middleware to override the config at runtime depending on domain match. Then I was sure to use the middleware priority in the kernal to run my middleware before start session.

Middleware

class SessionDomains
{
    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->getHost() === 'best4games.com'){
            config([
                'session.domain' => '.best4games.com'
            ]);
        }
        return $next($request);
    }
}

and in the http Kernal.php, add it at the top of your web middleware group:

    protected $middlewareGroups = [
        'web' => [
            SessionDomains::class,
        ],
    ];

and above start session in priority group

    protected $middlewarePriority = [
        SessionDomains::class,
        StartSession::class,
        ShareErrorsFromSession::class,
        Authenticate::class,
        ThrottleRequests::class,
        AuthenticateSession::class,
        SubstituteBindings::class,
        Authorize::class,
    ];

8 likes

Please or to participate in this conversation.