I'm trying to setup a workflow that does the following (must work in CI, ie. nothing exists before it runs):
- create a new DB with random name
- install new instance of my Laravel app to new random database name
- run my tests
- still have the test DB around to investigate issue after tests complete
- not have to juggle .env files or edit them in any way
EDIT: It's been suggested to let Laravel Test handle all this because it will wipe then migrate your DB but if I'm understanding correctly, this assumes that the DB already exists, ie. I have to manually create the DB, set it in .env THEN run my script to install the app and run tests. That is not the desired end goal/workflow.
I've got an Artisan command (gist here, cred to this post for a bunch of the code) that seemingly should do all of the above, except running the tests (can't get that far). You can see in the gist or below the numerous ways I've tried telling the command what database to connect to:
// $_ENV['DB_DATABASE'] = $dbname;
// $this->getLaravel()->environment(['DB_DATABASE' => $dbname]);
// $this->info('env: ' . $this->getLaravel()->environment('DB_DATABASE'));
// \Illuminate\Support\Env::enablePutenv();
// putenv('DB_DATABASE=' . $dbname);
// $this->info('env: ' . json_encode($_ENV));
// $this->call('config:clear');
config(['database.connections.' . $connection . '.database' => $dbname]);
What I'm finding is that every time I run the script, no matter how I try to tell the environment what DB to use, it will try to install overtop of my existing dev environment which is defined in my .env file. I want php artisan install --ready
to install into the new randomly named DB and for the tests to subsequently run using that DB.
What I'm finding though is that there isn't a way to dynamically tell Laravel or PHPUnit what database to use so this seems to a pointless endeavor. But it's such a common use case. How do Laravel devs handle this normally? A Node script that sets up the DB then copies/edits the .env and phpunit.xml files? Do it all in a CI env? I feel like I'm missing something.
EDIT: I've updated the gist to include the recommended change from Yahya's answer below which gets things working as desired, running DB:reconnect($connection)
after changing the config()
.