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
Artisan::call('config:cache');before changing the config. I think your configuration is already cached and that prevents it from changingconfig:cachebut get this error =[Symfony\Component\Debug\Exception\FatalErrorException] Declaration of Symfony\Component\Console\Input\ArrayInput::hasParameterOption() must be compatible with Symfony\Component\Console\Input\InputInterface::hasParameterOption($values, $onlyParams = false)config:cachefrom console to see if the same error is thrown.