在Laravel中.env配置文件是大家经常会用到的,但是使用它的时候一定不要在代码的逻辑层,env()只能使用在config目录下,env()只能使用在config目录下,env()只能使用在config目录下。
1.问题的出现
项目上线后发现局部的配置文件失效。
2.问题复现
先试用env()函数进行debug,获取到的配置部分失效。
3.问题排查
在本地的env()获取配置没有问题,怀疑运行是 php artisan config:cache 命令所致。
在服务器运行 php artisan config:clear 后所有获取.env配置获取正常。
定位为 php artisan config:cache 所致。
4.具体分析
对 php artisan config:cache 进行分析。
public function handle()
{
$this->call('config:clear'); //先运行清除
$config = $this->getFreshConfiguration(); //获取配置(关键在这里)
$configPath = $this->laravel->getCachedConfigPath(); //获取缓存配置写入路径
$this->files->put(
$configPath, '<?php return '.var_export($config, true).';'.PHP_EOL //生成配置
);
try {
require $configPath;
} catch (Throwable $e) {
$this->files->delete($configPath);
throw new LogicException('Your configuration files are not serializable.', 0, $e);
}
$this->info('Configuration cached successfully!');
}
/**
* Boot a fresh copy of the application configuration.
*
* @return array
*/
protected function getFreshConfiguration()
{
$app = require $this->laravel->bootstrapPath().'/app.php';
$app->make(ConsoleKernelContract::class)->bootstrap();
return $app['config']->all(); //获取配置
}
我们运行下getFreshConfiguration()方法。

得到了配置文件,但是配置文件只有在config下定义了的才会生成。
5.得出结论
php artisan config:cache 只能生成 config 中配置过的缓存文件。
当运行生成缓存后,env()只会去生成的缓存中获取配置。
综上所诉
不要在逻辑层直接使用env(),而要使用config()。