VOOZH about

URL: https://dzone.com/articles/configuring-multiple-database-connections-in-lumen

⇱ Configuring Multiple Database Connections in Lumen


Related

  1. DZone
  2. Data Engineering
  3. Data
  4. Configuring Multiple Database Connections in Lumen

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.

By Jul. 08, 16 · Tutorial
Likes
Comment
Save
23.5K Views

Join the DZone community and get the full member experience.

Join For Free

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');
Database connection

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

Opinions expressed by DZone contributors are their own.

Related

  • When Retries Become a Denial-of-Wallet
  • The Hidden Latency of Autoscaling
  • Database Connection Pooling at Scale: PgBouncer + Multi-Tenant Postgres (10K Concurrent Connections)
  • Spring Microservice Tip: Abstracting the Database Hostname With Environment Variable

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

Let's be friends: