For several console commands, I have the need to change databases so all my eloquent commands and queries run on the correct db (and server).
Ive seen a few solutions, the simplest seems to be changing the config like so:
$new_connection = [
'driver' => 'mysql',
'host' => '127.0.0.1',
'database' => 'test_db',
'username' => 'test',
'password' => 'test',
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
'strict' => false
];
config(['database.connections.mysql' => $new_connection]);
DB::purge('mysql');
The only issue (that I have noticed) is when I attempt to do transactions, more specifically, when I do transactions inside my acceptance tests in Codeception - they simply don't work.
The commands I use are:
DB::connection()->beginTransaction(); // inside the _before function
and
DB::connection()->rollBack(); // inside the _after function