0
0
Laravelframework~5 mins

.env file and environment variables in Laravel

Choose your learning style9 modes available
Introduction

The .env file stores settings that can change between environments, like your computer or a server. It helps keep sensitive info safe and makes your app flexible.

You want to keep your database password secret and not share it in your code.
You need different settings for your app when working on your laptop versus a live website.
You want to easily change the app's behavior without changing the code.
You want to store API keys safely outside your code files.
Syntax
Laravel
KEY=VALUE
ANOTHER_KEY=another_value
APP_NAME=MyLaravelApp
APP_DEBUG=true

Each line has a key and a value separated by an equals sign =.

Values are usually plain text. If they have spaces, wrap them in quotes.

Examples
Basic settings for app name, environment, and debug mode.
Laravel
APP_NAME=LaravelApp
APP_ENV=local
APP_DEBUG=true
Database connection settings stored safely in .env.
Laravel
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=mydb
DB_USERNAME=root
DB_PASSWORD=secret
Example showing a value with spaces wrapped in quotes.
Laravel
API_KEY="my secret key with spaces"
CACHE_DRIVER=file
Sample Program

This Laravel route reads APP_NAME and APP_DEBUG from the .env file using the env() helper. It shows how environment variables control app behavior.

Laravel
<?php

use Illuminate\Support\Facades\Route;

Route::get('/show-env', function () {
    $appName = env('APP_NAME', 'DefaultApp');
    $debugMode = env('APP_DEBUG', false) ? 'ON' : 'OFF';
    return "App Name: $appName, Debug Mode: $debugMode";
});
OutputSuccess
Important Notes

Never commit your .env file to public code repositories to keep secrets safe.

After changing .env, run php artisan config:cache to update settings.

Use the env() helper only in config files or service providers, not in your app logic directly for better caching.

Summary

The .env file stores environment-specific settings outside your code.

Use it to keep secrets safe and change app behavior easily.

Access variables with Laravel's env() helper.