如何在应用程序运行时使用Laravel连接到其他数据库? [英] How can I connect to a different database during application's runtime with Laravel?

查看:99
本文介绍了如何在应用程序运行时使用Laravel连接到其他数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,Laravel将连接到配置显示在.env文件中的数据库。但是,我希望将我的应用程序连接到数据库,该数据库的配置将通过HTTP(数据库主机,用户名,密码等)由其他内部服务提供。

By default Laravel will connect into a database whose configurations showed in .env file. However, I want to have my application connected to a database which configurations will be provided by other internal service through HTTP (database host, username, password, ...).

那么,如何在运行时将我的Laravel应用程序连接到数据库中?

So, how can I get my Laravel application connected into a database during runtime?

此线程:在Laravel中动态设置数据库连接和语言为我提供了使用中间件连接数据库的简单方法。但这并没有说明如何从Laravel代码的任何部分动态连接到数据库。

This thread: Set database connection and language dynamically in Laravel gives me a nutshell approach on using middleware to connect to a database. But it does not explain on how I can connect to a database dynamically from any part of my Laravel codes.

推荐答案

您可以使用Config :: set方法来即时更改基础配置-到另一个数据库连接,假设这就是您的意思。

You can use the Config::set method to change your underlying config on the fly - to another database connection, assuming that is what you mean.

Config::set("database.connections.mysql", [
    "host" => "...",
    "database" => "...",
    "username" => "...",
    "password" => "...
]);

这篇关于如何在应用程序运行时使用Laravel连接到其他数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆