Laravel supports multi-domain session handling out of the box, allowing you to share sessions across multiple domains or subdomains. This is particularly useful if you have a Laravel application that spans multiple related websites or applications.

To enable multi-domain session handling in Laravel, you need to configure the session settings in your config/session.php file. Specifically, you will set the domain option to the shared root domain that your applications will use. Let's walk through the steps:

  1. Set Up Shared Root Domain: Choose a shared root domain that will be used for all your applications. For example, if you have two applications with domains and, you could choose as the shared root domain.

  2. Configure config/session.php: Open the config/session.php configuration file. Look for the domain option, and set it to the shared root domain.

    // config/session.php 'domain' => '',

    The leading dot (.) before the domain name indicates that the session cookie should be accessible across all subdomains of the shared root domain.

  3. Set Cookie Domain Dynamically (Optional): If you need to set the cookie domain dynamically based on the current domain, you can do so in your AppServiceProvider or any other service provider that runs early in the application lifecycle.

    For example, you can use the following code to set the session cookie domain dynamically based on the current domain:

    // app/Providers/AppServiceProvider.php use Illuminate\Support\Facades\Config; public function boot() { $domain = '.' . request()->getHost(); // Get the current domain dynamically Config::set('session.domain', $domain); }

    This will ensure that the session cookie domain is set based on the current domain, allowing seamless session sharing across multiple domains.

  4. Configure CORS (Cross-Origin Resource Sharing) (Optional): If your applications are running on different domains and need to interact with each other via JavaScript, you may need to configure CORS to allow cross-origin requests.

    For Laravel applications, you can use the fruitcake/laravel-cors package or add appropriate CORS headers manually in your middleware.

With these configurations, your Laravel application should now support multi-domain session handling. Sessions set on one domain will be accessible on other domains within the shared root domain. Keep in mind that the session data itself is stored on the server, and the session cookie allows the client to maintain the session state across different domains.

Have questions or queries?
Get in Touch