Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 67 ยท Getting Started

Configuration and Environments

Learn how Laravel 13 reads .env files and config/ arrays, why env() belongs only in config files, what config:cache does, and what APP_KEY protects.

Every application has settings: the database to connect to, the name of the site, whether to show detailed errors, the key used to encrypt cookies. Some of these settings are the same everywhere, and some differ between your laptop, a test server and production. Laravel splits them into two layers: configuration files in config/ that describe what can be configured, and a .env file that supplies the values for this particular machine.

Getting this split right keeps secrets out of Git, makes deployment predictable, and avoids one of the most common Laravel surprises: an env() call that suddenly returns null in production. You will see why that happens, and how to avoid it.

Two layers

flowchart LR
    E[".env<br/>(per machine, secret)"] -->|"env('DB_HOST', 'localhost')"| C["config/database.php<br/>(per project, committed)"]
    C -->|"config('database.default')"| A["Your application code"]

Values live in .env; config files read them with env(); the rest of the app reads config files with config().

The .env file

.env is a plain text file with one KEY=value per line. It is not committed to Git; the repository contains .env.example as a template instead. A short excerpt:

INI
APP_NAME="My Shop"
APP_ENV=local
APP_KEY=base64:...
APP_DEBUG=true
APP_URL=http://my-shop.test

DB_CONNECTION=sqlite
MAIL_MAILER=log

Values with spaces need double quotes. When read with env(), the unquoted words true and false become PHP booleans, null becomes null, and empty becomes an empty string. Everything else is a string.

The config files

Each file in config/ returns an array. Here is a trimmed excerpt of config/app.php:

PHP
<?php

return [
    'name' => env('APP_NAME', 'Laravel'),
    'env' => env('APP_ENV', 'production'),
    'debug' => (bool) env('APP_DEBUG', false),
    'url' => env('APP_URL', 'http://localhost'),
    'timezone' => 'UTC',
    'locale' => env('APP_LOCALE', 'en'),
];

The second argument of env() is the default used when the key is missing. Note that timezone is not read from .env: it is the same on every machine, so it is just a value in code.

Reading configuration

Anywhere in your application, read a value with the config() helper and dot notation: the first part is the file name, the rest walks into the array.

PHP
$name = config('app.name');                     // "My Shop"
$driver = config('database.default');           // "sqlite"
$limit = config('services.stripe.limit', 100);  // default when the key is missing

config(['app.timezone' => 'Europe/Berlin']);    // set a value for this request only

Setting a value with config([...]) only lasts for the current request. It is never written to disk.

The golden rule: env() only inside config files

You can call env() anywhere, but you should only call it inside config/*.php. The reason is php artisan config:cache.

In production, you run php artisan config:cache during deployment (see Performance and Optimization). Laravel then merges all config files into one cached PHP file and stops loading .env entirely, so it does not have to parse it on each request. After that, any env('SOMETHING') call that lives outside a config file returns null. The code worked on your laptop and silently breaks in production.

PHP
// WRONG: breaks after config:cache
$key = env('STRIPE_SECRET');

// RIGHT: add it to config/services.php once...
'stripe' => ['secret' => env('STRIPE_SECRET')],

// ...and read it anywhere
$key = config('services.stripe.secret');

Following this rule also gives you one documented place for every setting.

After editing a config file or .env on a server where the config is cached, your change has no effect until you run php artisan config:cache again (or php artisan config:clear to turn caching off). On a local machine you normally do not cache the config at all.

Environments

APP_ENV names the environment: usually local, testing, staging or production. You can query it:

PHP
app()->environment();                    // "local"
app()->environment('local', 'staging');  // true if either matches
app()->isProduction();                   // true only in production

Common settings differ between environments:

Setting Local Production
APP_DEBUG true (detailed error pages) false
APP_ENV local production
LOG_LEVEL debug error or warning
MAIL_MAILER log (messages written to the log) a real mail service

Never run production with APP_DEBUG=true. The debug page can display environment values, SQL queries and file paths to anyone who triggers an error.

Tests use .env.testing or the <env> entries in phpunit.xml, which override .env while tests run (Testing with Pest).

APP_KEY

APP_KEY is the secret used by Laravel's encrypter. It protects encrypted cookies, signed URLs and any value you pass to Crypt::encryptString() or the encrypted Eloquent cast. Generate it once with php artisan key:generate.

Three rules apply:

  1. Never commit it, and never share it.
  2. Keep the same key across all servers that run the same application, or one server cannot read what another encrypted.
  3. Changing it invalidates existing sessions and anything encrypted with the old key, so rotate it deliberately.

Try it: a config repository

Laravel's config() is a repository around a nested array with dot-notation lookup. This stand-in has the same behaviour for get with a default, set and has, and also mimics the "cached config" trap by making env() return null once the cache is on.

PHP Dot notation, defaults and set

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Now the layering itself: an .env text, a config definition that uses env() with defaults, and what happens to stray env() calls once the config is cached.

PHP env() in config files, and the config:cache trap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The configuration array survives, but the stray env() call does not. In real Laravel, the cached array is loaded from a single file and .env is skipped, which is exactly this behaviour.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Where should you call env() in a Laravel application?

    After config:cache, .env is not loaded, so env() outside config files returns null. Config files keep every setting in one cached place.
  2. 2. What does config('database.connections.sqlite.database') do?

    The first segment is the file name; the remaining segments walk through nested array keys.
  3. 3. What should APP_DEBUG be in production?

    With debug on, error pages can expose queries, paths and environment details.
  4. 4. You set config(['app.timezone' => 'Asia/Tokyo']) in a controller. How long does the change last?

    Runtime config changes only affect the current process. They are never written to files.
  5. 5. What happens to existing sessions if you change APP_KEY?

    Sessions, encrypted cookies and anything encrypted with the old key become unreadable.

Summary

  • .env holds per-machine values and secrets; config/*.php files read them with env() and return arrays.
  • Read configuration with config('file.key.path', $default); runtime changes last for one request.
  • Call env() only inside config/, or php artisan config:cache will turn it into null.
  • APP_ENV names the environment, and APP_DEBUG must be false in production.
  • APP_KEY encrypts cookies and other data: generate it once, keep it secret, keep it identical across servers.

Next: Artisan and Custom Commands