I use Mac OS and Laravel Valet to develop my Laravel applications.
Part 1 is prerequisite configuration needed to make this work on your local environment.
Part 2 is framework configuration to enable session sharing across subdomains.
Let’s assume two projects, blog1 and blog2.
Assuming that Valet is already setup, navigating to blog1.test and blog2.test shows the respective app home pages.
Laravel allows to share session between subdomains, so if we could get blog1.test and blog2.test under one domain, the framework, under the right configuration, would do its magic and enable us to share same session across both apps.
I will not go into detail how to get your applications under same domain on production servers, since I feel there are many places you can find that information and relies on your cloud/hosting provider.
The first part of this tutorial is to get multiple projects under one domain, for example .blog.test.
At the end of this part, Valet should be able to serve our apps on blog1.blog.test and blog2.blog.test.
Essentially, we create symbolic links to our project folders and call valet link inside them.
The two projects:
- Make sure you go to each folder and do valet link
- valet links should show these two folders (and maybe more)
- cd /Users/xyz
- mkdir blog1.blog
- mkdir blog2.blog
- cd /Users/xyz/blog1.blog
- valet link
- cd /Users/xyz/blog2.blog
- valet link
- cd /Users/xyz/
- rm -rf blog1.blog
- rm -rf blog2.blog
- ln -s blog1 blog1.blog
- ln -s blog2 blog2.blog
- Navigate to blog1.blog.test and confirm you can load your app
- Navigate to blog2.blog.test and confirm you can load your app
Now we are ready to configure Laravel.
It’s important to note that the session data needs to be somewhere both applications can connect to even if they are on different servers. Therefore, the best solution would be to use redis or database.
The following configuration must be applied on both projects:
Both apps must use same APP_KEY:
Copy APP_KEY from blog1 to blog2
SESSION_DRIVER = database or redis
SESSION_COOKIE = blog_session
SESSION_DOMAIN = .blog.test
If you choose SESSION_DRIVER to be database, you will have to make sure you have a sessions table. You can do that by calling the following commands. Since the projects share the same database, you only have to run these in one project:
php artisan session:table
php artisan migrate
If you choose SESSION_DRIVER to be redis, you will have to make sure the name of the collection holding the sessions is the same. You will find this in cache.php:
CACHE_PREFIX = blog_cache
It didn’t make sense when I first saw this, but its the only way I could get it work.
You can now navigate to blog1.blog.test, login and then open blog2.blog.test. You are already logged in!
- Make sure you clear you cookies if you have had any unsuccessful attempts in your setup or configuration. It might also be a good idea to clear your sessions table if using database as SESSION_DRIVER. If using redis, you can flushall.