Laravel 动态更改连接
如何更改 laravel 的连接表单控制器,但存储在数据库中的连接信息,如数据库管理器,我的示例:
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();
推荐答案
我会在这里找一个帮手.让我们在 app/Helpers/DatabaseConnection.php
中创建一个.
I will go for a helper here. Let's create one in app/Helpers/DatabaseConnection.php
.
namespace AppHelpers;
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 AppHelpersDatabaseConnection;
...
$params = Database::find( 1 );
$connection = DatabaseConnection::setConnection($params);
$users = $connection->select(...);
注意:未经测试.我希望它有效或只是指导您
更多信息:
使用多数据库:https://laravel.com/docs/5.3/database#read-and-write-connections
动态设置配置:https://laravel.com/docs/5.3/configuration#accessing-configuration-values
相关文章