Laravel: connect to databases dynamically

Viewed 34030

I'm creating an application in Laravel 5(.1) where it is needed to connect to different databases. The only problem is that it's not known which databases it has to connect to, so making use of the database.php in config is not possible. A controller is in charge of making a connection with dynamically given connection details.

How can I make a new connection to a database, including making use of the DB class? (Or is this possible)

Thanks in advance!

5 Answers

You might need to use these:

use Illuminate\Support\Facades\Config;
use DB;

Set database configurations:

        Config::set("database.connections.mysql_external", [
            'driver' => 'mysql',
            "host" => "localhost",
            "database" => "db_name",
            "username" => "root",
            "password" => "root",
            "port" => '8889',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ]);

Connect to database and do stuff:

    $users = DB::connection('mysql_external')->select('Select id from users');

Disconnect database and reset config variables

        DB::disconnect('mysql_external');
        Config::set("database.connections.mysql_external", [
            'driver' => 'mysql',
            "host" => "localhost",
            "database" => "",
            "username" => "",
            "password" => "",
            "port" => '',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ]);

I ran into this problem too with a script that imports multiple MS Access DB files into MySQL and I was not satisfied with any of the solutions which suggested editing configuration at runtime. It was ugly and messy to dynamically create a new config for every single Access DB file that I wanted to import. After some playing, I manged to persuade Laravel to switch DBs on the existing connection like this:

$mysqlConn = DB::connection();
$mysqlConn->getPdo()->exec("USE $schemaName;");
$mysqlConn->setDatabaseName($schemaName);

//appServiceProvider.php

 Connection::macro('useDatabase', function (string $databaseName) {
            $this->getPdo()->exec("USE `$databaseName`;");
            $this->setDatabaseName($databaseName);
    });

//usage.

  \DB::connection()->useDatabase($dbName);
Related