Laravel Raw Database Connection

In a Laravel project, I needed to connect to multiple databases given the live configuration provided by the user. All comments found online were about invoking configurations saved in the proper config/database.php file, just not my case.

After a little investigation into the core code, I found this way to obtain a raw connections:

$factory = App::make('db.factory');

$config = [
        'driver' => $this->argument('driver'),
        'host' => $this->argument('host'),
        'username' => $this->argument('username'),
        'password' => $this->argument('password'),
        'database' => $this->argument('database'),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => false

$my_database = $factory->make($config);

(In this specific example I'm getting arguments for a console command and providing some default, but you got the point).

The key is that db.factory singleton of vendor/laravel/framework/src/Illuminate/Database/Connectors/ConnectionFactory.php inited in vendor/laravel/framework/src/Illuminate/Database/DatabaseServiceProvider.php; here more documentation about the notion of "singleton".