我想创建一个Laravel Web应用程序,允许管理员用户使用Web后端系统更改.env文件中的某些变量(如数据库凭据).但是我如何保存更改呢?
我想创建一个Laravel Web应用程序,允许管理员用户使用Web后端系统更改.env文件中的某些变量(如数据库凭据).但是我如何保存更改呢?
没有内在的方法可以做到这一点.如果您真的想更改.env
文件的内容,那么必须结合使用某种字符串替换和PHP的文件编写方法.要获得一些灵感,您应该看看key:generate
命令:KeyGenerateCommand.php:
$path = base_path('.env');
if (file_exists($path)) {
file_put_contents($path, str_replace(
'APP_KEY='.$this->laravel['config']['app.key'], 'APP_KEY='.$key, file_get_contents($path)
));
}
After the file path is built and the existence is checked, the command simply replaces APP_KEY=[current app key]
with APP_KEY=[new app key]
. You should be able to do the same string replacement with other variables.
Last but not least I just wanted to say that it might isn't the best idea to let users change the .env file. For most custom settings I would recommend storing them in the database, however this is obviously a problem if the setting itself is necessary to connect to the database.