$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[April 25, 2025] Laravel

Laravel Environment Configuration: Tips & Tricks

Laravel Environment Configuration: Tips & Tricks

────────────────────────────────────────────────────────

Laravel Environment Configuration: Tips & Tricks

Tip: .env.example as Documentation

Always keep .env.example in version control with all required keys.

Gotcha: Config Caching Breaks env() Calls

After php artisan config:cache, env() returns null outside config files. Only use env() in config files.

Tip: Environment-Specific Config

'driver' => env('MAIL_DRIVER', 'smtp'),

Use config files for defaults, .env for overrides.

Gotcha: .env is Not Recursive

Variable substitution like ${APP_URL}/api doesn't work in Laravel's .env parser.

Tip: config:clear Before config:cache

php artisan config:clear
php artisan config:cache

Clear old cache before building new one.

Gotcha: Different .env for Different Environments

Use .env.production, .env.staging, etc. Deploy scripts should copy the right one.

Tip: Use route:cache Carefully

php artisan route:cache is fast, but it doesn't work with closure-based routes. Every time you cache routes, Laravel serializes them. If you have Route::redirect() or closure callbacks, the cache breaks. Stick to controller-based routes in production.

Tip: Model APP_KEY Rotation

Rotating APP_KEY invalidates all encrypted data — cookies, encrypted DB columns, and password reset tokens. If you must rotate (e.g., after a leak), plan a migration that re-encrypts existing data with the new key.

Gotcha: Local Scope Leaks

Global scopes defined in booted() apply to ALL queries on that model — including relationships. An innocent User::all() in admin panel might exclude soft-deleted users if a global scope is active.

Senior Insight

The env() vs config() distinction has caused more production outages than any other Laravel gotcha in my career. I've seen teams use env('APP_DEBUG') directly in service providers, only to have it return null after config:cache runs. The rule is absolute: access all environment variables exclusively through config() in application code, and only use env() inside config files. Put this in your deployment checklist.

Source: Laravel News (https://laravel-news.com/), Freek.dev (https://freek.dev/tags/laravel), Spatie Blog (https://spatie.be/blog)

────────────────────────────────────────────────────────
<-- back to posts