DEV3 Technologies home

DEV3 Developer Forum

Why does env() return null after php artisan config:cache?

Laravel helpSolved0 views
dev3 ·

Locally env('STRIPE_KEY') works. On the server after running php artisan config:cache it returns null everywhere in my code, and some features break. The values are in .env. What is happening?

#laravel#configuration#deployment

0

1 reply

dev3 · Accepted answer

When config is cached, Laravel stops loading the .env file at all. The env() helper then only reads real environment variables, so any env() call outside the config/ files returns null (or its default).

Rule: call env() only inside files in config/. Everywhere else use config().

// config/services.php
'stripe' => [
    'key' => env('STRIPE_KEY'),
],

// anywhere else
$key = config('services.stripe.key');

Steps to fix

  1. Move each env('X') out of controllers, models and service classes into a config file.
  2. php artisan config:clear, then php artisan config:cache again (production only).
  3. If you change .env, run config:cache again, otherwise nothing changes.

Related notes

  • Do not run config:cache in local development, it makes .env changes appear to do nothing.
  • php artisan optimize caches config, routes, views and events together. optimize:clear removes all.
  • Closure-based routes cannot be cached (route:cache fails). Convert them to controller routes.
  • Values like true/false and null in .env are cast: (true), (false), (null), (empty). A string such as "false" quoted is still treated as false by env(), but after you move it into config use a proper cast: (bool) env('FEATURE') or filter_var.
  • In tests use config(['services.stripe.key' => 'test']) instead of changing env.

The Laravel .env generator is handy for building a clean production file.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.