Lumen - Create database connection at runtime

BernalCarlos picture BernalCarlos · May 13, 2016 · Viewed 15.4k times · Source

In a Lumen project, I need to create database connections on runtime, but I keep getting a "Database [...] not configured" error, each time I try to use a recently created connection.

This is my test code on routes.php:

<?php

$app->get('/', function () use ($app) {

    $config = $app->make('config');
    $config->set('database.connections.retail_db', [
        'driver'   => 'pgsql',
        'host'     => env('RETAIL_DB_HOST', 'localhost'),
        'port'     => env('RETAIL_DB_PORT', 5432),
        'database' => env('RETAIL_DB_DATABASE', 'forge'),
        'username' => env('RETAIL_DB_USERNAME', 'forge'),
        'password' => env('RETAIL_DB_PASSWORD', ''),
        'charset'  => env('RETAIL_DB_CHARSET', 'utf8'),
        'prefix'   => env('RETAIL_DB_PREFIX', ''),
        'schema'   => env('RETAIL_DB_SCHEMA', 'public'),
    ]);
    return app('db')->connection('retail_db')->select("SELECT * FROM users");

});

This code is supposed to work on Laravel, but I can't find any information regarding Lumen.

I'm using the latest Lumen version.

Answer

codedge picture codedge · May 15, 2016

There is one main problem with the method you are going for:

You did not initialize any configuration object. Lumen by default has no traditional config object set, until you create a config directory in your root folder.

As written in the Lumen configuration docs:

All of the configuration options for the Lumen framework are stored in the .env file.

The approach you are going for requires the traditional config object as used in Laravel.

To get that object and your new retail_db database connection working:

  • Create a config folder in your project root
  • Copy the file vendor/laravel/lumen-framework/config/database.php to this config folder
  • Initialize the database configuration object in your bootstrap/app.php with $app->configure('database'); (put it at line 28)

Your folder structure looks like this now:

├── app
├── bootstrap
├── config
   └── database.php
├── database
├── public
├── resources
├── storage
├── tests
└── vendor

Of course you can remove those connections you don't need from the connections array in app/config/database.php by commenting or removing them completely.

app/config/database.php

'connections' => [

        /*'testing' => [
            'driver' => 'sqlite',
            'database' => ':memory:',
        ],*/

        'sqlite' => [
            'driver'   => 'sqlite',
            'database' => env('DB_DATABASE', base_path('database/database.sqlite')),
            'prefix'   => env('DB_PREFIX', ''),
        ],

        'mysql' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'port'      => env('DB_PORT', 3306),
            'database'  => env('DB_DATABASE', 'forge'),
            'username'  => env('DB_USERNAME', 'forge'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => env('DB_CHARSET', 'utf8'),
            'collation' => env('DB_COLLATION', 'utf8_unicode_ci'),
            'prefix'    => env('DB_PREFIX', ''),
            'timezone'  => env('DB_TIMEZONE', '+00:00'),
            'strict'    => env('DB_STRICT_MODE', false),
        ],
]

Your bootstrap/app.php with the changes:

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new Laravel\Lumen\Application(
    realpath(__DIR__.'/../')
);

//$app->withFacades();
// $app->withEloquent();

$app->configure('database');

Now you can use the code you already have in your routes.php.

To delete your retail_db connection, just set it to null:

$config->set('database.connections.retail_db', null);