0
0
Laravelframework~5 mins

Environment configuration in Laravel

Choose your learning style9 modes available
Introduction

Environment configuration helps your Laravel app know important settings like database info or app mode. It keeps these details separate from your code so you can change them easily.

When you want to set different database connections for local and live sites.
When you need to switch between debug mode on your computer and off on the live server.
When you want to keep secret keys safe and not share them in your code.
When deploying your app to different servers with different settings.
When you want to change app settings without changing the code.
Syntax
Laravel
# .env file example
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:randomkeyhere
APP_DEBUG=true
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=secret

The .env file holds key=value pairs for settings.

Laravel reads these values automatically using env('KEY') in code.

Examples
This tells Laravel the app is running in production mode.
Laravel
# Set app environment
APP_ENV=production
Turns off detailed error messages for users.
Laravel
# Set debug mode
APP_DEBUG=false
Configures Laravel to connect to a PostgreSQL database.
Laravel
# Database settings
DB_CONNECTION=pgsql
DB_HOST=192.168.1.10
DB_PORT=5432
DB_DATABASE=mydb
DB_USERNAME=user
DB_PASSWORD=pass
Sample Program

This Laravel route returns some environment settings as a JSON response. It shows how to access .env values using the env() helper.

Laravel
<?php

use Illuminate\Support\Facades\Route;

Route::get('/env-info', function () {
    return [
        'app_name' => env('APP_NAME'),
        'app_env' => env('APP_ENV'),
        'debug_mode' => env('APP_DEBUG') ? 'On' : 'Off',
        'database' => env('DB_CONNECTION'),
    ];
});
OutputSuccess
Important Notes

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

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

Use different .env files for local, staging, and production environments.

Summary

Environment configuration stores app settings outside code for easy changes.

Laravel uses a .env file with key=value pairs for this.

Access settings in code with the env() helper function.