Sharing a session between subdomains in laravel is a common usecase and there are many questions with accepted answers here on stackoverflow. But all the solutions provided don't work for me. I have a login page on http://localhost/login
and a admin dashboard on http://admin.localhost/dashboard/overview
All solutions suggests to set the SESSION_DOMAIN
environment variable ( or in config/session.php the domain
value ) to .example.com
or for me to .localhost
.
I did that but it does not work.
If I login I can see in the database that a new session entry is created with a valid user_id. When I navigate to the dashboard a new entry is created and a Forbidden response is returned because my middleware steps in. The expected behaviour is that the same session is used and not another is created.
I don't know if that changes anything but I also added the subdomain to my hosts file. I also cleared my cache and my browser cookies.
If I look into the Forbidden response from the dashboard via the chrom dev tools I can see that the server returns the cookies with the .localhost
as it's domain attribute, but the cookie is not set because "[...] the cookie's domain attribute was invalid with respect to the current host URL." ( translated )
Try to use 127.0.0.1 Instead of localhost
Browsers treat localhost differently than regular domains, but 127.0.0.1
behaves more like a standard domain.
Update your hosts
file to map admin.localhost
to 127.0.0.1
:
127.0.0.1 localhost
127.0.0.1 admin.localhost
Access your application via http://127.0.0.1/login and http://admin.127.0.0.1/dashboard.