Akkua
Akkua

Reputation: 141

What could possibly cause getenv to fail when the variable is present in .env file?

I have an .env file containing SOME_IP=127.0.0.1:8080. In a Laravel controller for a certain request I call $foo = getenv('SOME_IP');. About 90% of the time it works fine, I get the string and proceed. But the other 10% of times, getenv returns false, even though the variable is clearly in the .env file. What could be causing this?

Alternatively, Laravel's env returns null.

Observed with vlucas/phpdotenv v2.6.4.

Upvotes: 0

Views: 563

Answers (1)

Maybe it's because of caching the config. It is better to load your env variable in a config file and then retrieve it from the config. For example you can create a file with the name 'ips' in config directory like this:

<?php
return ['someIp' => env('SOME_IP')];

and then use

$foo = config('ips.someIp')

Upvotes: 1

Related Questions