如何在laravel数据库.php文件中动态添加连接

2022-06-16 00:00:00 multi-tenant database php laravel

我需要用PHP代码把连接动态追加到lobase.php文件中,行不行?


解决方案

我正在使用它 当我创建新客户时

public function setConnection($tenantName){
    //GET Database Connection file path
            $path = config_path('database.php');
            //GET Database Connection file 
            $arr = include $path;
            // load the array from the file
            $new_connection=[
                'driver'    => 'mysql',
                'host'      => env('DB_HOST'),
                'database'  => $tenantName,
                'username'  => env('DB_USERNAME'),
                'password'  => env('DB_PASSWORD'),
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
                'strict' => false
            ];
            // modify the array
            $arr['connections'][$tenantName]=$new_connection;
           // write it back to the file
            file_put_contents($path, "<?php  return " . var_export($arr, true) . ";");
    }

相关文章