如何在Laravel中动态更改.env文件中的变量? [英] How to change variables in the .env file dynamically in Laravel?

查看:631
本文介绍了如何在Laravel中动态更改.env文件中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个Laravel Web应用程序,允许管理员用户使用Web后端系统更改.env文件中的某些变量(例如数据库凭据).但是,如何保存更改?

I want to create a Laravel web app that allows an admin user to change some variables(such as database credentials) in the .env file using the web backend system. But how do I save the changes?

推荐答案

没有内置的方法可以做到这一点.如果您确实要更改.env文件的内容,则必须结合使用PHP的文件写入方法和某种字符串替换.为了获得一些启发,您应该看一下key:generate命令:

There is no built in way to do that. If you really want to change the contents of the .env file, you'll have to use some kind of string replace in combination with PHP's file writing methods. For some inspiration, you should take a look at the key:generate command: 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)
    ));
}

建立文件路径并检查其存在之后,该命令将APP_KEY=[current app key]替换为APP_KEY=[new app key].您应该能够用其他变量进行相同的字符串替换.
最后但并非最不重要的一点是,我只是想说让用户更改.env文件不是最好的主意.对于大多数自定义设置,我建议将它们存储在数据库中,但是,如果设置本身是连接数据库所必需的,那么这显然是一个问题.

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.

这篇关于如何在Laravel中动态更改.env文件中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆