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.