Lumen - Create database connection at runtime

21,485

Solution 1

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);

Solution 2

To answer @jhon's question Lumen does not provides that config folder, you need to create at root the new directory called config.

Then inside it just copy what @codedge mentions about database.php file

Copy the file vendor/laravel/lumen-framework/config/database.php to this config folder

follow below commands in terminal to create the config directory and copy the database.php file

user$ cd projectPath/
user$ mkdir config
user$ cp vendor/laravel/lumen-framework/config/database.php config/database.php

where this config folder is the config directory you just created. so it would looks like the image below. folder structure

Share:
21,485
BernalCarlos
Author by

BernalCarlos

Updated on April 07, 2021

Comments

  • BernalCarlos
    BernalCarlos about 3 years

    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.

  • BernalCarlos
    BernalCarlos almost 8 years
    Thank you @codedge this is what i need. But out of curiosity, how can i delete the newly created connection?
  • codedge
    codedge almost 8 years
    For deleting there is only the way, setting it to null - I updated, my answer.
  • Kamlesh
    Kamlesh about 5 years
    how can we use $config = $app->make('config'); in controller's action?, please tell me. Thanks.
  • Kamlesh
    Kamlesh about 5 years
    Put database.php file at config/database.php instead of app/config/database.php location and do not forget to comment/delete db credentials in .env file and restart lumen services by command line. It works. Thanks @codedge.
  • jhon
    jhon about 3 years
    Hello, I'm using Lumen 8.2.3, when I create new project, I don't see config/database.php or config file, should I create new one? or there is command for create config file? thanks