問題描述
我在我的項目中使用了一個包,它在 config/packagename
我想在配置文件中動態更改這個值,這是當前文件結構的樣子;
'118754561','cache_lifetime_in_minutes' =>60*24,];
我想把它改成這樣 -
'view_id' =>身份驗證::用戶()-> id,
您可以在配置文件中執行此操作,還是必須存儲某種變量以便稍后在控制器中更新.有沒有辦法將這些變量放在 env 文件中并從控制器訪問這些新變量?
這也是一個動態更新 .env 文件的通用解決方案(分別是單獨的鍵/值對)
- 像這樣更改 config/packagename 中的設置:
<塊引用>
返回 ['view_id' =>環境('VIEW_ID','118754561'),等等...]
在 .env 中添加一個初始值:
VIEW_ID=118754561
在適當的控制器(例如 AuthController)中,使用下面的代碼并像這樣調用函數:
updateDotEnv('VIEW_ID', Auth::User()->id)
受保護的函數 updateDotEnv($key, $newValue, $delim=''){$path = base_path('.env');//從當前環境中獲取舊值$oldValue = env($key);//有什么變化嗎?如果($oldValue === $newValue){返回;}//用改變的數據重寫文件內容如果(文件存在($路徑)){//用新值替換當前值file_put_contents($path, str_replace($key.'='.$delim.$oldValue.$delim,$key.'='.$delim.$newValue.$delim,file_get_contents($path)));}}
(如果您想讓此函數更通用,以便使用 .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;
<?php
return [
'view_id' => '118754561',
'cache_lifetime_in_minutes' => 60 * 24,
];
I would like to change it to something like this -
'view_id' => Auth::user()->id,
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:
return [ 'view_id' => env('VIEW_ID', '118754561'), etc... ]
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)
protected function updateDotEnv($key, $newValue, $delim='') { $path = base_path('.env'); // get old value from current env $oldValue = env($key); // was there any change? if ($oldValue === $newValue) { return; } // rewrite file content with changed data if (file_exists($path)) { // replace current value with new value file_put_contents( $path, str_replace( $key.'='.$delim.$oldValue.$delim, $key.'='.$delim.$newValue.$delim, file_get_contents($path) ) ); } }
(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 動態配置設置的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!