Laravel - Change Database Connection for a specific URL?

前端 未结 2 900
野性不改
野性不改 2021-01-03 12:04

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

2条回答
  •  再見小時候
    2021-01-03 12:32

    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

提交回复
热议问题