I am using Laravel 5.5 and I need to change database dynamically,
For example, there are two databases,db1 and db2,there is a table articles in each database.
Now I want to copy articles from db1 to db2,
in .env file, the current database is db1:
DB_DATABASE=db1
I want to change it dynamically when copying records, I tried to do it like this:
public function test()
{
$articles=Article::all();
Config::set("database.connections.mysql", [
"host" => "127.0.0.1",
"database" => "db2",
"username" => "root",
"password" => ""
]);
//DB::purge('mysql'); //this line exists or not,it has the same error.
DB::table('articles')->insert($articles);
dd('ok');
}
but there is an error:
Undefined index: driver
I have many databases, so I don't want to change it in .env file.
What should I do?
update:
in config/database.php it has the two items:
'default' => env('DB_CONNECTION', 'mysql'),
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
],
and I try
Config::set("database.connections.mysql", [
'mysql' => [
"host" => "127.0.0.1",
"database" => "db2",
"username" => "root",
"password" => ""
]
]);
The error still exists.
'default' => env('DB_CONNECTION', 'mysql')present in config/database.php ?