Laravel - Change Database Connection for a specific URL?

前端 未结 2 901
野性不改
野性不改 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:31

    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.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题