Don't use the config helper in a config file

Unless you like empty config values

Joel Clermont
Joel Clermont

It's a rule that has been ingrained in my mind: always use the config() helper and never use the env() helper.

Why? Well when you get to production, and you cache your configuration, all calls to env() for keys in your .env file will return null.

But yesterday I was debugging an issue where calls to config() were returning null, even locally. And it wasn't a typo or anything like that.

The issue was that the call to config() was inside another config file. Why is that relevant?

When Laravel boots and process your config files, it processes them one at a time, in alphabetic order. So config/app.php is always processed before config/auth.php.

In my case, there was a config file for a package that was trying to load values from config/filesystems.php, but because of ordering, config/filesystems.php hadn't been processed yet, so my call to config('filesystems.some_key') returned null.

The solution was simple, just use env() directly instead of trying to leverage the existing config setup.

Technically, you could play the ordering game and reference config values as long as you know it's been processed first, but that feels like a bad idea.

I now have a new complementary rule ingrained in my mind: never use the config() helper in config files, always use env() there instead.

Here to help,


P.S. Step-debugging got me to a quick solution here. If you've never set it up, I highly recommend it. I gave a whole talk about Xdebug for the Laravel worldwide meetup.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.