How to Use Environment Variables in Laravel Easily
In Laravel, environment variables are stored in the
.env file and accessed using the env() helper function or configuration files. This allows you to keep sensitive data like API keys and database credentials outside your codebase securely.Syntax
Environment variables in Laravel are defined in the .env file as key-value pairs. You access them in your PHP code using the env('KEY', 'default') function, where KEY is the variable name and default is an optional fallback value.
For example, env('APP_NAME', 'Laravel') returns the value of APP_NAME or 'Laravel' if not set.
dotenv / php
APP_NAME=MyLaravelApp APP_DEBUG=true DB_HOST=127.0.0.1 // Access in PHP $appName = env('APP_NAME', 'DefaultApp'); $debugMode = env('APP_DEBUG', false);
Example
This example shows how to define environment variables in the .env file and access them in a Laravel controller to display the app name and debug mode status.
php
// .env file APP_NAME=MyLaravelApp APP_DEBUG=true // app/Http/Controllers/ExampleController.php namespace App\Http\Controllers; use Illuminate\Http\Request; class ExampleController extends Controller { public function show() { $appName = env('APP_NAME', 'Laravel'); $debug = env('APP_DEBUG', false) ? 'enabled' : 'disabled'; return "App Name: $appName, Debug Mode is $debug."; } }
Output
App Name: MyLaravelApp, Debug Mode is enabled.
Common Pitfalls
- Forgetting to restart the server or clear config cache after changing
.envvariables can cause old values to persist. - Using
env()directly in production code outside config files is discouraged; instead, use config files to cache values. - Not committing
.env.examplefile with sample variables can confuse team members.
php
// Wrong: Using env() directly in views or many places $apiKey = env('API_KEY'); // Right: Use config files (config/services.php) return [ 'api_key' => env('API_KEY'), ]; // Then access via config helper $apiKey = config('services.api_key');
Quick Reference
| Action | Example | Description |
|---|---|---|
| Define variable | APP_NAME=MyApp | Set key-value in .env file |
| Access variable | env('APP_NAME', 'Default') | Get value with fallback |
| Use in config | 'name' => env('APP_NAME') | Load env in config files |
| Cache config | php artisan config:cache | Refresh cached config after changes |
| Avoid direct env() | Use config('key') | Better for performance and caching |
Key Takeaways
Store sensitive data in the .env file and never commit it to version control.
Access environment variables using env() in config files, then use config() in your app.
Run php artisan config:cache after changing .env to apply updates.
Avoid calling env() directly in your application code outside config files.
Keep a .env.example file with sample keys for team reference.