Laravel - 更改特定 URL 的数据库连接?

Laravel - Change Database Connection for a specific URL?(Laravel - 更改特定 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 的数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)