Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

Another way to lazy load a config fallback value

Built right into Laravel's env helper

Joel Clermont
Joel Clermont
2025-12-16

From our daily Laravel tips email. Get the next one in your inbox.

Last week, I shared a pattern for lazy loading a backup configuration value.

This approach does work, but shortly after publishing it I realized there's an even cleaner way to achieve the same result using Laravel's built-in env() helper.

This helper natively supports a closure as the default value! So instead of using ?? from my previous solution, you can do this instead:

'some_key' => env('SOME_ENV_VAR', fn () => expensiveLookupFunction()),

When you pass a closure, Laravel will only call it if the environment variable is not set.

Both these solutions produce the same basic result, but since Laravel gives us a tool to do it, I would stick with the built-in functionality.

Here to help,

Joel

P.S. Tinkerwell is a handy tool for interactively testing out code snippets like this.

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.