I’m developing a web app using Laravel. I’ve set an API key in my .env file, which is correctly placed in the root directory. I’m able to retrieve and view the API key in the browser using a test route:
Route::get('/test-env', function () {
$envValue = env('OPEN_AI_KEY');
return "Environment Variable Value: $envValue";
});
However, when I try to run one of my crucial business logic scripts in my CLI, which includes the identical env(‘[MY_ENV_KEY]’) function and parameter, I get NULL returned.
I’ve tested with several environment keys, and all of them show up in the browser using the /test-env route, but all return NULL in my CLI.
I have tried using iTerm2 and the VSCode terminal to rule out a problem with the particular CLI.
I’ve tried getenv() instead, which also works in my /test-env route but returns bool(false) for all .env keys in my CLI.
For reference, this is the relevant portion of the class that is instantiated in the script I’m trying to run in my CLI:
$openAiKey = env('OPEN_AI_KEY');
var_dump($openAiKey);
exit;
As recommended per similar questions, I’ve tried running:
php artisan config:clear
php artisan cache:clear
php artisan optimize:clear
I’ve also tried restarting my development server.
I’m expecting the value of the .env key to show up in the CLI, confirming that the script is successfully fetching it, just as the /test-env route can, but I keep getting NULL or bool(false).