Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sandaur's avatar

Which is the better way to access environment variables?

Hello,

i was reading Laravel - Code Smart 2016 by Dayle Rees when i come across with this statement:

"If you wanted to, you could certainly stick to env(), however, this way(referring to use env() over config() to access environment variables) you won’t be able to make use of the caching functionality of Laravel’s configuration layer. You see, Laravel can cache your configuration files to make the framework more performant. However, it can’t cache values from environmental variables, so if you choose to use env() outside of the PHP configuration files then you might end up getting yourself in a caching mess. We don’t want that, do we?"

So, is this true? because everywhere i see there are people accessing env variables with env() from all kind of places (controllers, views, etc).

Is it better to create a file in config/, access env from there and then use config() to access cached env variables?

Are only the variables in config/ files cached?

0 likes
3 replies
sandaur's avatar

Then those who use env() outside the config/ directory are not taking advantage of the cache feature?

Cronix's avatar

Nope, or when they do they wonder why everything suddenly stops working lol.

It's just best to use env() only in config files, and access values via config() helper in the app. Then it won't matter if one day you decide to cache the config. Everything will still work. It's better than the opposite and deciding to cache the config and having to rework everything.

Please or to participate in this conversation.