Laravel动态更改连接

时间:2017-02-13 06:42:53

标签: php database laravel connection

如何更改laravel的连接表单控制器,但存储在数据库中的连接信息,如数据库管理器,我的例子:

我的数据库中有数据库信息:

id, driver, database_name, username, password, host

所以在我的控制器上只需致电:

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

2 个答案:

答案 0 :(得分:12)

我会在这里寻求帮助。让我们在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');
    }
}

现在控制器中的某处我们尝试

use App\Helpers\DatabaseConnection;
... 

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

注意:未经测试。我希望它有效或只是引导你

更多信息:

答案 1 :(得分:1)

谢谢,EddyTheDove,我在使用您的解决方案,这很不错:)只是为了知道如何选择表名,我正在为此

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

现在在控制器中的某个地方尝试

使用App \ Helpers \ DatabaseConnection; ...

    $params['connection_name'] = 'onthefly';
    $params['dbname'] ='dbname';
    $params['driver'] = 'mysql';
    $params['host'] = 'localhost';
    $params['username'] = 'root';
    $params['password'] = '';
    $params['port'] = 3306;

$connection = DatabaseConnection::setConnection($params);
$getTableData = $connection->table('table_name')->where("column_name",'=','matchCondition')->get();