Connecting Laravel to Multiple Databases the Right Way

Laravel supports multiple database connections cleanly. Here's how to set them up, route models to the right database, and avoid the common pitfalls.

Richard GamoraRichard GamoraFullstack developer·4 min read
LaravelDatabaseArchitecture

It is common to outgrow a single database. A separate analytics warehouse, a legacy database you cannot retire, or a read replica for reporting all push you toward multiple connections. Laravel supports this cleanly, but the configuration has subtleties that are easy to get wrong.

Defining connections in config/database.php

Each connection is a key in the connections array. Beyond your default mysql connection, you might add a reports connection that points at a read replica, or a legacy connection for an older system. Set DB_HOST and DB_DATABASE for each in your .env.

Routing models to a connection

Set the $connection property on a model to bind it to a specific database. ReportItem extends Model and sets protected $connection = 'reports'. Now every query on ReportItem goes to the reports connection, no matter where it is called from.

For ad hoc queries, use DB::connection('reports')->select(...) directly. This is fine for one-offs but I prefer to encapsulate the connection inside a model or repository so the connection name does not leak across the codebase.

Migrations and the --database flag

By default, php artisan migrate runs against your default connection. To run against another, use --database=reports and put migrations for that connection in a separate folder (database/migrations/reports). This keeps schemas separate and prevents accidental mixing.

The transaction trap

DB::transaction() only wraps queries on the connection it was called on. If a closure inside the transaction also queries another connection, those queries are not part of the transaction and will not roll back. This is the most common bug I see.

If you need consistency across two databases, you usually do not actually need it — you need a single source of truth and an eventual sync to the other. Cross-database transactions are a sign that the data model needs adjusting.

About the author

Richard Gamora

Richard Gamora

Fullstack developer based in the Philippines, working mostly with Laravel and Vue.js, with eight years of production experience across web and mobile.

me@richardgamora.comUpwork ↗

More on Laravel