Laravel-更改特定URL的数据库连接? [英] Laravel - Change Database Connection for a specific URL?

查看:436
本文介绍了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.

有人可以帮我吗?

推荐答案

我将通过以下方式进行操作:

I would do it the following way:

将允许的国家/地区列表放入配置文件(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的数据库连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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