Laravel 动态配置设置
问题描述
我在我的项目中使用了一个包,它在 config/packagename
我想在配置文件中动态更改这个值,这是当前文件结构的样子;
我想把它改成这样 -
您可以在配置文件中执行此操作,还是必须存储某种变量以便稍后在控制器中更新.有没有办法将这些变量放在 env 文件中并从控制器访问这些新变量?
这也是一个动态更新 .env 文件的通用解决方案(分别是单独的键/值对)
- 像这样更改 config/packagename 中的设置:
<块引用>
在 .env 中添加一个初始值:
VIEW_ID=118754561
在适当的控制器(例如 AuthController)中,使用下面的代码并像这样调用函数:
updateDotEnv('VIEW_ID', Auth::User()->id)
(如果您想让此函数更通用,以便使用 .env 中的 key=value 对,其中值必须用双引号括起来,因为它们包含空格,则需要 $delim 参数).
诚然,如果您有多个用户同时在您的项目中使用这个包,这可能不是一个好的解决方案.所以这取决于你使用这个包的目的.
注意:如果您打算从其他类中使用它,当然需要将该函数公开.
I'm using a package within my project and it stores a setting inside config/packagename
I would like to dynamically change this value inside the config file, this is how the file structure looks currently;
I would like to change it to something like this -
Can you do this within the config file, or do you have to store some sort of variable to be updated later within a controller. Is there a way to place these variables in an env file and access these new variables from a controller?
This also is a generic solution to dynamically update your .env file (respective the individual key/value pairs)
- Change the setting in your config/packagename like so:
Add an initial value into .env:
VIEW_ID=118754561
In an appropriate controller (e.g. AuthController), use the code below and call the function like this:
updateDotEnv('VIEW_ID', Auth::User()->id)
(The $delim parameter is needed if you want to make this function more generic in order to work with key=value pairs in .env where the value has to be enclosed in double quotes because they contain spaces).
Admittedly, this might not be a good solution if you have multiple users at the same time using this package in your project. So it depends on what you are using this package for.
NB: You need to make the function public of course if you plan to use it from other classes.
这篇关于Laravel 动态配置设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!