Skip to content

Month: January 2020

Laravel 使用 env 函式讀取環境變數為 null 的問題

在 Laravel 專案中,如果執行了 php artisan config:cache 命令把配置檔案快取起來後,在使用 env 函式讀取環境變數的值,會變成 null,但是執行 php artisan config:clear,清除配置快取後,又可以讀取了,就覺得很奇怪 看了一下,得知在 Laravel 中,如果執行 php aritisan config:cache 命令後,Laravel 就會把 app/config 目錄下的所有配置檔案快取到 bootstrap/cache/config.php 裡面。正因為有了這個快取配置檔案,在其他地方使用 env 函式,就會讀取不到環境變數,所以返回 null. 接著看一下 Illuminate/Foundation/Bootstrap/DetectEnvironment.php 的這段程式碼:   public function bootstrap(Application $app) { if (! $app->configurationIsCached()) {…