---
title: Use config() Helper, Never env() Outside Config Files
impact: HIGH
impactDescription: config caching (php artisan config:cache) breaks env() calls at runtime — app silently returns null
tags: config, env, caching, laravel, environment
---

## Use config() Instead of env() Outside Config Files

`env()` only works reliably before config is cached. Once you run `php artisan config:cache` (required in production), `env()` returns `null` everywhere except in `config/*.php` files.

**Wrong:**

```php
// Service class — breaks after config:cache
class PaymentService
{
    public function charge()
    {
        $key = env('STRIPE_SECRET'); // NULL in production!
    }
}

// Controller
public function show()
{
    $debug = env('APP_DEBUG'); // NULL after config:cache
}
```

**Correct:**

```php
// 1. Define in config/services.php
return [
    'stripe' => [
        'secret' => env('STRIPE_SECRET'),  // env() ONLY here
    ],
];

// 2. Use config() everywhere else
class PaymentService
{
    public function charge()
    {
        $key = config('services.stripe.secret'); // always works
    }
}

// 3. With default fallback
$debug = config('app.debug', false);
```

**Rule:** `env()` appears only in `config/` directory. Everywhere else → `config()`.
