【问题标题】:Dynamic database connection in LaravelLaravel 中的动态数据库连接
【发布时间】:2016-11-11 05:17:18
【问题描述】:

我知道在 Laravel 中,您可以通过在 config/database.php 文件中指定多个数据库连接,然后使用 DB::connection('my_conn_name') 来使用多个数据库连接,但是无论如何要使用 config/database.php 文件中未指定的连接?

我正在编写一个归档应用程序,因此用户可以指定他们想为进程使用的连接(主机、用户和密码),我希望我可以从show databases 返回提供的结果连接。

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    用户指定 db 参数后,您可以将其存储在会话中以在 config/database.php 填充自定义连接:

    'connections' => [
    
        'mysql' => [
            '...'
        ],
    
        'testing' => [
            '...'
        ],
    
        'custom' => [
            'driver'    => 'mysql',
            'host'      => session()->get()->db_host,
            'database'  => session()->get()->db_database,
            'username'  => session()->get()->db_username,
            'password'  => session()->get()->db_password,
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ]
    
    ]
    

    【讨论】:

      猜你喜欢
      • 2016-07-05
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      • 1970-01-01
      • 2018-12-07
      • 2020-05-07
      • 2015-08-09
      相关资源
      最近更新 更多