Multiple DB Connections in Laravel

Here is how to run more than one database connection.

This article is about using databases with different data, not necessary for load balancing (or connection pooling) between databases.

Define Connections

Inside of your datbase configuration file – likely app/config/database.php – you can define more than one database connection of any type. In fact, you can define as many connections as you’d like. For instance, if your application has to pull data from 2 MySQL databases, you can define them both separately:

We have our default connection still set to mysql. This means that, unless we specify otherwise, the application will use thet mysql connection.

Specify Connection

Now that we have a 2nd database connection setup – how do we use it in code?

It turns out there’s a few ways!

Schema

Within the Schema Builder, you can use the with any connection. To specify which connection to use, simply run the connection() method:

Query

Similar to Schema Builder, you can on the Query Builder:

Eloquent

You can also define to use in your Eloquent models as well!

One way is to set the variable in your model:

You can also define the connection at runtime via method.

databasem,laravel,database connectitng
Be careful about attempting to build relationships with tables across databases! It is possible to do, but it can come with some caveats and depends on what database and/or database settings you have.

2 thoughts on “Multiple DB Connections in Laravel”

Leave a Comment