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:cachestops.envloading.env()only inconfig/*.php.- Use
config()in application code.
More most-asked Laravel questions
- How do you validate requests in Laravel? Why use Form Requests?
- Gates or policies: how does authorization work in Laravel?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- How do database transactions work in Laravel, and what pitfalls should you know?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- What is the service container, and how does dependency injection work in Laravel?
- What is the N+1 query problem in Eloquent and how do you prevent it?
- How do queues work in Laravel?