所以这是玩弄这个之后的最终解决方案。
我的控制器:
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');
}
}
新的磁盘驱动程序:
要在项目根目录创建一个新文件,我必须创建一个新的磁盘驱动程序。我在config/app.php 文件中添加了以下代码:
'disks' => [
.....
'root' => [
'driver' => 'local',
'root' => base_path(),
],
],
这使我能够使用以下方法在根目录创建新文件:
Storage::disk('root')->put('filename', $content);
总结:
所以基本上我正在获取 .env.example 文件的内容,更改我想要的常量的值,然后创建一个新的 .env 文件。之后,我运行了所有的迁移和种子。
注意:
由于愚蠢的错误No supported encrypter found. The cipher and / or key length are invalid.,我不得不手动设置APP_KEY
由于我试图在代码中执行所有操作,而不是通过命令 - 我尝试使用 Artisan::call('key:generate'); 但由于一些奇怪的原因它无法解决问题,我不得不手动创建一个随机字符串,即 32有点长,设置为APP_KEY。
希望这对其他人有所帮助。 :)
感谢@rypskar 的帮助。