Laravel interview question · Most asked

Why should you not call env() outside configuration files?

Summary

Because after php artisan config:cache the .env file is no longer loaded, so env() returns null everywhere except inside the cached config. Read environment values into config/*.php and use config('services.stripe.key') in code.

Longer Answer

Config caching (done in every production deploy) compiles all config files into one PHP array and skips loading .env on each request, which is faster. Code that calls env('STRIPE_KEY') directly works locally and silently gets null in production.

Centralising values in config files also documents which variables the app uses, lets you set defaults, and makes values easy to override in tests with config([...]).

Key Points

  • config:cache stops .env loading.
  • env() only in config/*.php.
  • Use config() in application code.

More most-asked Laravel questions

← All Laravel questions