Environment Configuration (.env file)
Every Laravel application needs settings that change depending on where it's running — a local database on your laptop looks nothing like a production database in the cloud. Laravel manages this through a single file: .env.
Purpose of .env
The .env file stores environment-specific configuration as simple key-value pairs, kept separate from the application's core code. Laravel's configuration files in config/ read values from .env at runtime, so the same codebase can behave differently in local, staging, and production environments without any code changes.
Common Variables
| Variable | Purpose |
|---|---|
| APP_ENV | Identifies the current environment (local, staging, production) |
| APP_KEY | A unique encryption key used to secure sessions and data |
| APP_DEBUG | Toggles detailed error output, disabled in production |
| DB_CONNECTION | Specifies the database driver, such as mysql or pgsql |
| DB_HOST / DB_DATABASE | Defines where and which database to connect to |
| MAIL_MAILER | Sets the driver used for sending outgoing email |
Best Practices
- Never commit
.envto version control — it should stay unique per environment - Keep an
.env.examplefile in the repository as a template for other developers - Set
APP_DEBUGto false in production to avoid leaking sensitive error details - Rotate the
APP_KEYonly with care, since it affects encrypted data and sessions
Once the environment is configured correctly, the application is ready to actually respond to requests — which starts with defining routes in web.php and api.php.
How Laravel Loads the File
Understanding the loading order explains most .env surprises:
- On boot, Laravel uses the phpdotenv library to read
.envfrom the project root. - If a file such as
.env.testingmatches the currentAPP_ENV, Laravel loads that one instead. PHPUnit and Pest runs use this to point tests at a separate database. - Real server environment variables take priority over values in the file, so hosting platforms can inject secrets without a file at all.
- Files in
config/callenv()to read the values and store them in the configuration repository. - The rest of the application reads settings with
config().
Reading Values the Right Way
Add a new setting in two places. First the .env file:
APP_NAME="Shop Admin"
PAYMENT_API_URL=https://sandbox.example-payments.test
PAYMENT_API_KEY=replace-me
MAIL_FROM_NAME="${APP_NAME}"
Values with spaces need quotes, and ${APP_NAME} reuses another variable. Then expose it through a config file such as config/services.php:
'payment' => [
'url' => env('PAYMENT_API_URL', 'https://sandbox.example-payments.test'),
'key' => env('PAYMENT_API_KEY'),
],
Finally, read it anywhere in the app:
$url = config('services.payment.url');
if (app()->environment('production')) {
// production-only behaviour
}
The second argument to env() is a default used when the variable is missing.
Why env() Belongs Only in Config Files
In production you should run php artisan config:cache. It merges all config files into one cached file for faster boots. After caching, the .env file is no longer loaded, so any env() call inside a controller, model or view returns null. Code that worked locally then breaks on the server. Keeping env() inside config/ and using config() everywhere else avoids this completely.
Useful commands while working with environments:
php artisan key:generate # create APP_KEY for a fresh install
php artisan config:clear # drop the cached config after edits
php artisan about # show current environment and cache status
php artisan env:encrypt # create an encrypted copy of .env
The encrypted copy can be committed safely, while the decryption key is stored in your deployment platform's secret store.
Errors Developers Commonly Hit
- Edits not taking effect: the config is cached; run
config:clearor rebuild the cache. - "No application encryption key":
APP_KEYis empty; generate one. - Broken values: an unquoted value with spaces or a
#character gets cut off. - Tests wiping real data: create
.env.testingwith its own database before running tests. - Exposed file: make sure the web server's document root is the
public/folder, so.envcan never be downloaded.
Checklist: template in .env.example, secrets only in .env or server variables, env() only in config, config cached on deploy, and debug turned off in production.
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.