logo

Another way to lazy load a config fallback value

Built right into Laravel's env helper

Joel Clermont
Joel Clermont
2025-12-16

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.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice.