Laravel - Change Database Connection for a specific URL?

∥☆過路亽.° 提交于 2019-12-08 06:13:27

问题


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'

Now, if the url becomes - example.com/country - I want the default database connection to become - 'db2'

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.

Could someone help me out here?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/25890952/laravel-change-database-connection-for-a-specific-url

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