Laravel is a powerful PHP framework known for its elegant syntax and developer-friendly features. In real-world applications, sometimes one database isn’t enough. You might need to connect to multiple databases — for load balancing, microservices, legacy systems, or simply keeping things modular.
In this article, you’ll learn how to configure and use multiple databases in Laravel 12, with real-life examples.
🔧 Step 1: Define Multiple Connections in config/database.php
Open your config/database.php
file. Under the connections
array, you can define multiple databases. Here's how you can define a MySQL and a secondary PostgreSQL connection.
Now update your .env
file accordingly:
🧠 Step 2: Use a Different Connection in a Model
Let’s say you have a Product
model that belongs to the main MySQL database and a Report
model that should connect to the secondary PostgreSQL database.
This will ensure Laravel uses the correct database connection for each model.
🚀 Step 3: Querying Data from Multiple Databases
You can now query like this:
🛠️ Step 4: Running Migrations on a Specific Database
If you want to run migrations on the pgsql_secondary
connection, use the --database
option:
You can create separate migrations for multiple database connections.
Default Connection
Second Database Connection
🧪 Bonus: Using Query Builder or Raw Queries on Another Connection
You can also use Laravel’s DB facade:
📝 Conclusion
Laravel 12 makes it easy to manage multiple databases with a clean configuration and expressive query system. Whether you’re scaling your app, handling reporting systems, or integrating legacy data, Laravel’s database abstraction handles it all elegantly.
📚 References
If you found this helpful, feel free to share or drop a comment. Happy coding with Laravel! 🧱✨
Social Plugin