Configuring Multiple Database Connections In Lumen

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

// Use mysql2 connection
Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial


  1. Roy Heuer says:

    Thank you so much for this. Quick question - can Eloquent still be used with this approach?

    1. Paul says:

      Hi Roy, Eloquent isn't used in Lumen by default you need to turn it on manually.

Leave a Reply

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