Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lumen - Create database connection at runtime

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.

like image 400
BernalCarlos Avatar asked May 13 '16 16:05

BernalCarlos


People also ask

Should I use lumen or Laravel?

Lumen is a micro framework, used to develop micro-services and API development in high speed and less time. Lumen declines the SQL queries cant perform tuining on databases, less featured compare to Laravel. Laravel is better for building RESTful APIs. Lumen is better for building high performing micro framework API.

Does lumen have eloquent?

Of course, you may easily use the full Eloquent ORM with Lumen. To learn how to use Eloquent, check out the full Laravel documentation.


2 Answers

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);
like image 119
codedge Avatar answered Oct 17 '22 00:10

codedge


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

like image 28
Felipe Arturo Perez Camargo Avatar answered Oct 17 '22 01:10

Felipe Arturo Perez Camargo