DEV Community

Cover image for [Common mistake] Sharing session across multiple Laravel subdomain
EJEH
EJEH

Posted on

[Common mistake] Sharing session across multiple Laravel subdomain

To Share session across domain and it's multiple especially when you have large ecosystem were multiple applications communicate with one database So when a user authenticates any of these apps, they will be logged in everywhere.

For example, when a user AUTH into http://mywebsite.com, he or she can easily access the rest of the sub hosted site directly say http://dashboard.mywebsite.com or http://subdomain.mywebsite.com.

Actually it's easy to share session on Laravel by following this steps. Basically you need the exact same sessions configuration in all of your applications, also the same encryption key.

1) Open your .ENV and add the following:
SESSION_DRIVER=database
SESSION_DOMAIN=.domain.com
Example as shown session on Laravel
(Dont forget Make sure to include a dot(.) before your domain name.)

2) Store the sessions in the database
This command will create a migration for your sessions:

=> First generate a migration file
php artisan session:table

=>Now, migrate generated sessions table
php artisan migrate

That’s it. You are done.
Don’t forget to clear the cookies for all of your apps before you start testing. Example below
session on Laravel

Common mistake and check you should notice whenever you follow the after steps and your session isn't sharing.

Make you Update application keys
Make sure the “APP_KEY” variable in your .env file has the same value in all your applications. Just copy one and paste it everywhere.

Don't forget to use same "APP_NAME" across you applications, otherwise it will not work, laravel use APP_NAME to generate cookies and cookies name should be same to make it work propertly.

DELETE config.php inside your laravel project bootstrap/cache folder.

And that's it.. with above checks you are go to go.

Top comments (0)