Using Multiple Database Connections in Laravel
Step 1: Set Up Database Connections in .env
In your root .env file, define both primary and secondary database credentials like this:
Step 2: Configure Connections in config/database.php
Add the second connection in the connections array:
Step 3: Get Data from the Second Database
You can now query data from both connections:
Example: Primary DB
Example: Secondary DB
Bonus: Use Models with Custom Connection
If you're using Eloquent models, you can specify the connection like this:
Now you can call:
Summary
| Task | Command / Code |
|---|---|
| Define DBs | .env variables |
| Configure | config/database.php |
| Query Secondary DB | DB::connection('mysql2')->table('table')->get() |
| Use in Model | protected $connection = 'mysql2'; |

