沃梦达 / 编程问答 / php问题 / 正文

Laravel 动态更改连接

Laravel Change Connection Dynamically(Laravel 动态更改连接)

本文介绍了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

这篇关于Laravel 动态更改连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Laravel 动态更改连接

基础教程推荐