How to use multiple databases in PHP Laravel?

Spread the love

Sometimes, we want to use multiple databases in PHP Laravel.

In this article, we’ll look at how to use multiple databases in PHP Laravel.

How to use multiple databases in PHP Laravel?

To use multiple databases in PHP Laravel, we can create an .env file with the config for all the databases.

Then we can reference the .env values in config/databases.php.

For instance, we write

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database1
DB_USERNAME=root
DB_PASSWORD=secret

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

in .env to add the database info and credentials.

Tnen in config/databases.php, we add

//...
'mysql' => [
    'driver'    => env('DB_CONNECTION'),
    'host'      => env('DB_HOST'),
    'port'      => env('DB_PORT'),
    'database'  => env('DB_DATABASE'),
    'username'  => env('DB_USERNAME'),
    'password'  => env('DB_PASSWORD'),
],

'mysql2' => [
    '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'),
],
//...

to add both database configs.

Conclusion

To use multiple databases in PHP Laravel, we can create an .env file with the config for all the databases.

Then we can reference the .env values in config/databases.php.

Leave a Reply

Your email address will not be published. Required fields are marked *