Laravel - Change Database Connection for a specific URL?

隐身守侯 提交于 2019-12-08 05:48:28

I would do it the following way:

Put the list of allowed countries into config file (countries.php) .

In 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
     });

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

I've made something similar using environments.

Add a new rule when detecting the environment to parse the URL and change it to the new environment. Then you can add a directory for the new environment where you set up the new database, base URL, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!