So here is the final solution after playing around with this.
My controller:
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Storage;
class TestController extends Controller
{
public function index() {
// Values I want to insert
$data = [
'APP_KEY' => str_random(32),
'DB_HOST' => 'localhost',
'DB_DATABASE' => 'lara_test',
'DB_USERNAME' => 'root',
'DB_PASSWORD' => ''
];
// default values of .env.example that I want to change
$defaults = ['SomeRandomString', '127.0.0.1', 'homestead', 'homestead', 'secret'];
// get contents of .env.example file
$content = file_get_contents(base_path() . '/.env.example');
// replace default values with new ones
$i = 0;
foreach ($data as $key => $value) {
$content = str_replace($key.'='.$defaults[$i], $key.'='.$value, $content);
$i++;
}
// Create new .env file
Storage::disk('root')->put('.env', $content);
// run all migrations
Artisan::call('migrate');
// run all db seeds
Artisan::call('db:seed');
dd('done');
}
}
New Disk Driver:
To create a new file at project root, I had to create a new Disk Driver. I added following code in my config/app.php
file:
'disks' => [
.....
'root' => [
'driver' => 'local',
'root' => base_path(),
],
],
and this enabled me to create new file at root by using:
Storage::disk('root')->put('filename', $content);
Summary:
So basically I am getting the contents of .env.example file, changing the values of constants I want and then creating a new .env file. After that I ran all my migrations and seeds.
Note:
I had to manually set the APP_KEY
because of a stupid error No supported encrypter found. The cipher and / or key length are invalid.
Since I am trying to do everything inside code, not through commands - I tried using Artisan::call('key:generate');
but for some strange reasons it didn't work so to fix the issue, I had to create a random string manually which is 32 bit long and set it as APP_KEY
.
Hope this will help someone else. :)
And thanks to @rypskar for assistance.