Skip to content
Advertisement

How to append connection dynamically in database.php file in laravel

I need to append dynamically connection in the database.php file using PHP code, is it possible or not?

Advertisement

Answer

It is working for me When I create a new customer then

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) . ";");
    }

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement