我尝试从根目录中的 .env 获取环境变量
Route::get('/test', function () {
return "value is". getenv('APP_ENV');
});
和
Route::get('/test', function () {
return "it is". env('APP_ENV');
});
它在 .env 中
APP_NAME=Laravel
APP_ENV=local
我怎样才能访问它?
最佳答案
使用 Laravel,您应该避免配置文件之外的环境变量。
在配置文件中,您可以使用环境变量,例如 config/app.php:
'env' => env('APP_ENV', 'production'),
然后您可以使用配置助手来访问它:config('app.env')
。
这允许您缓存配置并仍然访问这些值,因为 env('APP_ENV')
将一旦您的配置被缓存就不再起作用。
如docs提及:
"If you execute the
config:cache
command during your deployment process, you should be sure that you are only calling theenv
function from within your configuration files. Once the configuration has been cached, the.env
file will not be loaded and all calls to theenv
function will returnnull
."
关于Laravel - 访问 .env 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51987140/