Laravel 不从不同的环境文件中读取环境变量
Laravel not reading env variables from different env files
从 5.0 升级到 5.8 后,如果 env 与 .env 文件不同,laravel 将停止读取 env 变量。
例如,如果我有 .env
文件,其中包含 USE_SSL=true
。
env('USE_SSL')
将为真
但是如果我 .env
文件指向另一个环境:
APP_ENV=dev
然后我会有 .env.dev
包含 USE_SSL=true
的文件,env('USE_SSL')
将为空。
- 我尝试了
composer dump-autoload
和 php artisan config:clear
,以及 php artisan config:cache
- 没有成功。缓存与否,我无法获取值。
- 我尝试将文件命名为 .dev.env 和 .env.dev - 没有成功。
如有任何想法,我们将不胜感激。
好吧,如果你真的想这样做,
Route::get('renderEnvChaining',function(){
$myCustomEnv = parse_ini_file(base_path(env('CUSTOM_ENV')));
return $myCustomEnv['USE_SSL']; // This will return true
});
我在我的 .env 文件中提到了这一点,
CUSTOM_ENV=.env.example
现在我默认env.example我把这个
USE_SSL="true" // This will return true
USE_SSL=true // This will return 1
刚刚发现.ini和.env遵循相同的值,所以我将.env文件解析为.ini文件,
试一试,我以前从未做过这件事,请在 运行 进入生产服务器之前与其他开发人员联系
我将其添加为答案,但请注意不是根据laravel 文档应如何使用 .env 文件。由于某些限制要求我为每个环境使用不同的配置文件,并在运行时加载它,这只是我需要使用的一种方式。要正确使用 .env 文件,请检查 docs.
这是一种在运行时加载不同配置文件的方法,具体取决于 APP_ENV 指向的位置。我将其标记为已回答,因为它正在回答这个特定问题。
.env
APP_ENV=specific_domain
.env.specific_domain
USE_SSL=true
Http/Kernel.php
public function __construct(Application $app, Router $router)
{
parent::__construct($app, $router);
$app_env = explode("=", file($app->environmentFilePath(), FILE_IGNORE_NEW_LINES)[0])[1];
$app->loadEnvironmentFrom(".env.$app_env");
}
从 5.0 升级到 5.8 后,如果 env 与 .env 文件不同,laravel 将停止读取 env 变量。
例如,如果我有 .env
文件,其中包含 USE_SSL=true
。
env('USE_SSL')
将为真
但是如果我 .env
文件指向另一个环境:
APP_ENV=dev
然后我会有 .env.dev
包含 USE_SSL=true
的文件,env('USE_SSL')
将为空。
- 我尝试了
composer dump-autoload
和php artisan config:clear
,以及php artisan config:cache
- 没有成功。缓存与否,我无法获取值。 - 我尝试将文件命名为 .dev.env 和 .env.dev - 没有成功。
如有任何想法,我们将不胜感激。
好吧,如果你真的想这样做,
Route::get('renderEnvChaining',function(){
$myCustomEnv = parse_ini_file(base_path(env('CUSTOM_ENV')));
return $myCustomEnv['USE_SSL']; // This will return true
});
我在我的 .env 文件中提到了这一点,
CUSTOM_ENV=.env.example
现在我默认env.example我把这个
USE_SSL="true" // This will return true
USE_SSL=true // This will return 1
刚刚发现.ini和.env遵循相同的值,所以我将.env文件解析为.ini文件,
试一试,我以前从未做过这件事,请在 运行 进入生产服务器之前与其他开发人员联系
我将其添加为答案,但请注意不是根据laravel 文档应如何使用 .env 文件。由于某些限制要求我为每个环境使用不同的配置文件,并在运行时加载它,这只是我需要使用的一种方式。要正确使用 .env 文件,请检查 docs.
这是一种在运行时加载不同配置文件的方法,具体取决于 APP_ENV 指向的位置。我将其标记为已回答,因为它正在回答这个特定问题。
.env
APP_ENV=specific_domain
.env.specific_domain
USE_SSL=true
Http/Kernel.php
public function __construct(Application $app, Router $router)
{
parent::__construct($app, $router);
$app_env = explode("=", file($app->environmentFilePath(), FILE_IGNORE_NEW_LINES)[0])[1];
$app->loadEnvironmentFrom(".env.$app_env");
}