paulund

Using Env

Using Env

The .env file is the standard place to store environment-specific configuration in Laravel. It keeps sensitive values out of your codebase and lets you change behaviour across environments without touching a single line of PHP.

The .env File

Laravel ships with a .env.example file that documents every variable your application expects. When you clone a project, copy it to .env and fill in the values:

cp .env.example .env
php artisan key:generate

The .env file must never be committed to version control. Add it to .gitignore (Laravel does this for you by default).

env() vs config() — Know the Difference

The env() helper reads directly from the .env file or from the system environment. It works reliably during development, but it stops working after you run php artisan config:cache in production. The cached config file replaces all environment lookups.

The rule is simple: use env() only inside config files under the config/ directory. Everywhere else in your application, use config().

// ✅ Good — config/services.php reads env() once
return [
    'stripe' => [
        'key'    => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
    ],
];

// ✅ Good — application code reads from the config cache
$secret = config('services.stripe.secret');

// ❌ Bad — env() called outside a config file; breaks after config:cache
class PaymentService
{
    public function getSecret(): string
    {
        return env('STRIPE_SECRET'); // Will return null in production
    }
}

Providing Default Values

Both env() and config() accept a second argument as a fallback:

// In a config file
'timeout' => env('API_TIMEOUT', 30),

// In application code
$timeout = config('services.api.timeout', 30);

Caching Config in Production

Running config:cache serialises every config file into a single cached file. This dramatically speeds up application bootstrap. Always run it as part of your deployment:

php artisan config:cache

If you change a .env value on the server, clear the cache afterwards:

php artisan config:clear

Validating Required Variables

Laravel does not enforce that every variable in .env.example is present in .env. A missing value silently becomes null. For critical variables, add validation in your config files or a dedicated service provider:

// config/services.php
$stripeSecret = env('STRIPE_SECRET');

if (app()->isProduction() && empty($stripeSecret)) {
    throw new \RuntimeException('STRIPE_SECRET must be set in production.');
}

return [
    'stripe' => [
        'secret' => $stripeSecret,
    ],
];

Quick Reference

Do this Not this
config('app.name') env('APP_NAME') in app code
env() in config/ files env() in controllers or services
Commit .env.example Commit .env
Run config:cache in production Skip caching on the production server