/    Sign up×
Bounties /Pin to ProfileBookmark

What is the correct way to connect to multiple databases in Laravel?

If I want to have multiple databases in one system, how would I do this? The databases wouldn’t necessarily be all SQL.

to post a answer
Laravel

1 Replies

Copy linkTweet thisAlerts:
@JacobBarkerAug 11.2022 — I encountered this in a recent project:
You would have to define a second database connection in config/database.php
'otherdb' => [
'driver' => env('DB_CONNECTION_SECOND'),
'host' => env('DB_HOST_SECOND'),
'port' => env('DB_PORT_SECOND'),
'database' => env('DB_DATABASE_SECOND'),
'username' => env('DB_USERNAME_SECOND'),
'password' => env('DB_PASSWORD_SECOND'),
],


And then define those values in your .env file:
DB_CONNECTION_SECOND=mysql
DB_HOST_SECOND=127.0.0.1
DB_PORT_SECOND=3306
DB_DATABASE_SECOND=database2
DB_USERNAME_SECOND=root
DB_PASSWORD_SECOND=secret

You can change the DB_CONNECTION_SECOND (and effectively the driver on the otherdb connection) to a different driver (for example sqlite)

You can then use the second connection in the query builder: $users = DB::connection('otherdb')->select(...); or set the model's connection property: protected $connection = 'otherdb'; to use it with eloquent.
In order to use this with migrations as well, set the connection on the Schema: Schema::connection('otherdb')->create('some_table', function($table)
{
$table->increments('id'):
});
×

Success!

Help @ReilyAcevedo spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.1,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...