Laravel Change Connection Dynamically

2019-01-18 14:38发布

问题:

How to change laravel's connection form controller but the connection information stored at database like database manager, my example :

I have a databases information on my database :

id, driver, database_name, username, password, host

so at my controller just call :

$connection = Database::find( 1 );
$users = new Users();
$users->setConnection( [
    'driver' => $connection->driver,
    'host' => $connection->host,
    'username' => $connection->username,
    'password' => $connection->password
] );
$users = $users->get();

回答1:

I will go for a helper here. Let's create one in app/Helpers/DatabaseConnection.php.

namespace App\Helpers;
use Config;
use DB;

class DatabaseConnection
{
    public static function setConnection($params)
    {
        config(['database.connections.onthefly' => [
            'driver' => $params->driver,
            'host' => $params->host,
            'username' => $params->username,
            'password' => $params->password
        ]]);

        return DB::connection('onthefly');
    }
}

And now somewhere in controller we try

use App\Helpers\DatabaseConnection;
... 

$params = Database::find( 1 );
$connection = DatabaseConnection::setConnection($params);
$users = $connection->select(...);

Note: Not tested. I hope it works or simply guide you

More info:

  • Using multi database: https://laravel.com/docs/5.3/database#read-and-write-connections

  • Setting configurations on the fly: https://laravel.com/docs/5.3/configuration#accessing-configuration-values