Laravel - 访问 .env 变量

标签 laravel laravel-5 environment-variables

我尝试从根目录中的 .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 the env function from within your configuration files. Once the configuration has been cached, the .env file will not be loaded and all calls to the env function will return null."

关于Laravel - 访问 .env 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51987140/

相关文章:

android - 在 gradle 中读取系统环境变量

mysql - Eloquent ORM,deleted_at 使用软删除时没有索引

Laravel 在 Laravel 之前捕获错误

laravel-5 - AbstractProvider.php 第 200 行中的 Laravel Socialite InvalidStateException

php - 获取laravel中带有特定标签的所有数据

php - 在 Laravel 5.1 中获取过滤和关联的记录

linux - 导出的变量未反射(reflect)在 "env"输出中

Laravel:在行子集上同步多对多

html - CSS 导航栏图像问题

python - 在 Linux 中通过管道设置和使用环境变量