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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:37:55  来源:igfitidea点击:

Laravel does not read env variables

laravelenvironment-variablesartisan

提问by wujt

Did anyone has issues with envvariables? For some reason, helper env('VARIABLE')returns nullevery 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:cachecommand during your deployment process, you should be sure that you are only calling the env()function from withinyour configuration files.

如果执行php artisan config:cache过程中您的部署过程中的命令,你应该确保你只调用env()从函数的配置文件。

Obviously I have envvariables outside the config files, so after caching I was not able to use it outside anymore. The php artisan config:clearputs 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 envvariables 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:cacheeach time you will change .envfile. 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');