Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Configuring Multiple Database Connections in Lumen

DZone's Guide to

Configuring Multiple Database Connections in Lumen

Connecting to one database in Lumen is easy enough, but what about connecting to multiple databases? Come find out how to handle this situation.

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

In Lumen you can create a database connection by filling out the default information you can find in .env file. But if you need multiple database connections you can do so by adding a new database config file and creating a list of the new database connections.

Create a database config file /config/database.php.

Add an array of database information.

return [
    'default' => 'mysql',
    'connections' => [
        'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST'),
            'database' => env('DB_DATABASE'),
            'username' => env('DB_USERNAME'),
            'password' => env('DB_PASSWORD'),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
        ],
        'mysql2' => [
            'driver' => 'mysql',
            'host' => env('DB2_HOST'),
            'database' => env('DB2_DATABASE'),
            'username' => env('DB2_USERNAME'),
            'password' => env('DB2_PASSWORD'),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
        ],
    ]
];

By setting a default element will allow you to choose which database to use when you call DB::connection();. By placing the env() function inside the configuration file you can manage the database credentials on a per environment basis.

To use the different databases in your code you need to define which connection you want by passing in the name of the connection by either using the app() helper function or the DB facade.

// Use default connection
app('db')->connection()->select('xx');
DB::connection()->select('yy');

// Use mysql2 connection
app('db')->connection('mysql2')->select('xx');
DB::connection('mysql2')->select('yy');

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

Topics:
databases ,database ,file ,config ,connections

Published at DZone with permission of Paul Underwood, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}