Laravel - Change Database Connection for a specific URL?(Laravel - 更改特定 URL 的数据库连接?)
问题描述
我对使用 laravel 框架相当陌生.我有以下要求.我有一个域 - example.com,它的整个代码堆栈都在 laravel 中运行.假设在配置默认数据库连接是 - 'db1'
I am fairly new to using laravel framework. I have the following requirement. I have a domain - example.com, and its entire code stack is running in laravel. Lets say in the config default database connection is - 'db1'
现在,如果 url 变为 -example.com/country - 我希望默认数据库连接变为 - 'db2'
Now, if the url becomes - example.com/country - I want the default database connection to become - 'db2'
我还希望将基本 URL 更改为 example.com/country,因为所有模块都将是相同的.这里只有数据库连接会发生变化.
And also I want the base URL to be changed to example.com/country, since all the modules are going to be the same. Only the database connection is going to change here.
有人可以帮我吗?
推荐答案
我会这样做:
将允许的国家列表放入配置文件(countries.php
).
Put the list of allowed countries into config file (countries.php
) .
在routes.php
:
// choosing country
$country = '';
if (in_array(Request::segment(1), Config::get('countries'))) {
$country = Request::segment(1);
}
// making route for top level
if ($country != '') {
Route::any( '/', 'MainPage@index');
}
// making routes optionally prefixed by country
Route::group(
array('prefix' => $country,
function () {
// here all routes
});
在您定义了连接的 database.php
中,您可以添加另一个连接,例如:
In database.php
where you have defined your connection you could add another connections for example:
'germany' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'germany_connection',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
现在在同一个文件中(尽管您可能应该将它移到其他地方)您可以这样做:
Now in the same file (although you should probably move it somewhere else) you can do:
if ($country == 'germany') {
DB::disconnect();
Config::set('database.default','germany');
DB::reconnect();
}
您当然可以在这里添加许多条件,或者如果您为每个允许的国家/地区定义了连接,您可以简单地这样做:
You can of course add many conditions here or if you have defined connection for each allowed country you can simply do:
if ($country != '' ) {
DB::disconnect();
Config::set('database.default', $country);
DB::reconnect();
}
应该可以,但是我没有测试过
It should work however I haven't tested it
这篇关于Laravel - 更改特定 URL 的数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel - 更改特定 URL 的数据库连接?
基础教程推荐
- 超薄框架REST服务两次获得输出 2022-01-01
- 在多维数组中查找最大值 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01