Laravel 不读取环境变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42935205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel does not read env variables
提问by wujt
Did anyone has issues with env
variables? For some reason, helper env('VARIABLE')
returns null
every time I use it. It happened very unexpectedly and I dont really know the reason. Restarting the apache/IDE/computer does not work.
有没有人有env
变量问题?出于某种原因,每次我使用helperenv('VARIABLE')
时null
都会返回。它发生的非常意外,我真的不知道原因。重新启动 apache/IDE/计算机不起作用。
回答by wujt
The solution is simple, but not IDE nor debugger tells anything about it. It just returns null
. When you use php artisan config:cache
, according to documentation:
解决方案很简单,但 IDE 和调试器都没有说明。它只是返回null
。当您使用时php artisan config:cache
,根据文档:
If you execute
php artisan config:cache
command during your deployment process, you should be sure that you are only calling theenv()
function from withinyour configuration files.
如果执行
php artisan config:cache
过程中您的部署过程中的命令,你应该确保你只调用env()
从函数中的配置文件。
Obviously I have env
variables outside the config files, so after caching I was not able to use it outside anymore. The php artisan config:clear
puts it back to work.
显然我env
在配置文件之外有变量,所以缓存后我不能再在外面使用它了。这php artisan config:clear
让它恢复工作。
What I've found more about the usage of env
, that it should be used onlywithin config files. You can access env
variables from the rest of the project using other helper method config()
. Be sure to assign it to another key in config file, e.g. 'key' => env('CACHE_DRIVER')
我发现更多关于 的用法env
,它应该只在配置文件中使用。您可以env
使用其他辅助方法从项目的其余部分访问变量config()
。确保将它分配给配置文件中的另一个键,例如'key' => env('CACHE_DRIVER')
What is more, you have to remember to run php artisan config:cache
each time you will change .env
file. Laravel will not load the new values, until it's cached. If it's not cached, no need to do it.
更重要的是,您必须记住php artisan config:cache
每次更改.env
文件时都运行。Laravel 不会加载新值,直到它被缓存。如果它没有被缓存,就没有必要这样做。
回答by Majbah Habib
Run those of command
运行那些命令
composer dump-autoload
php artisan cache:clear
php artisan config:clear
php artisan view:clear
Now try to read
现在尝试阅读
$value = env('VARIABLE_NAME');
if not working till now then,
如果现在不工作,
Try another syntaxto read env variable.
尝试另一种语法来读取 env 变量。
$value=getenv('VARIABLE_NAME');