How to connect two Laravel 8 applications sharing same database

Laravel is an amazing application with so many built-in functionalities. Also, it enables developers to implements robust functionalities very easily.

Here in this article, we will show you how to connect two Laravel application sharing login details and sessions across sub-domains.

Lets say we have two laravel applications

1) reporting.example.com
2) video.example.com

We will connect both applications in 3 easy steps.

1: Share APP_KEY across both applications

Generate/Share APP_KEY on both applications and this should be same. If you don’t have APP_KEY already generated, you can use the following command to generate a new one.

php artisan key:generate --show

copy the key and paste it in .env files in both appications.

APP_KEY=basic64:xksjslsksjxxxxxxxxxxxxxxxx

2) Config/sessions.php

Next we will change the value of domain element in config/sessions.php file. let say our main domain is example.com. we will add .example.com. Remember, do not miss (.) before domain name.

3) Session managed in database

Now we will change the sessions in both laravel application. we need to change the value of SESSION_DRIVER value from file to database. once we change it, next we need to make sure we have sessions table in the database. If we do not have already, we can create one with the following command.

php artisan session:table

above command will create session migration file, ready to migarte table in the database. Below command will migrate the session table

php artisan migrate

Note: if you already have sessions table in the database, clear the table, to make the changes work.

4) Clear Cache

Now we need to clear the cache and browser cache to test both applications.

php artisan optimize:clear
php artisan config:clear