Configuration
Environment Configuration
Environment configuration allows you to manage settings for different environments (local, staging, production) without changing code. Laravel uses the .env file for this purpose.
- Store sensitive and environment-specific settings in the
.envfile (e.g., database credentials, API keys). - Never commit the
.envfile to version control. Use.env.examplefor sharing default settings. - Access environment variables using
env('KEY')in config files.
Example .env file:
APP_NAME=LaravelApp
APP_ENV=local
APP_KEY=base64:...
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Best Practices:
- Use different
.envfiles for each environment. - Document required environment variables in
.env.example. - Use secure values for production (e.g., strong APP_KEY).
Configuration Files
Configuration files in config/ define application settings and options. Always use environment variables for sensitive or environment-specific values.
// Good
return [
'key' => env('CONFIG_KEY', 'default_value'),
'api_url' => env('API_URL', 'https://api.example.com'),
];
// Bad
return [
'key' => 'hardcoded_value',
'api_url' => 'https://api.example.com',
];
- Group related settings in separate config files (e.g.,
config/database.php,config/mail.php). - Use sensible defaults for optional settings.
- Document config options with comments.
Example: Custom Config File
Create a custom config file in config/custom.php:
return [
'feature_enabled' => env('FEATURE_ENABLED', false),
'max_items' => env('MAX_ITEMS', 100),
];
Access config values in code:
if (config('custom.feature_enabled')) {
// Feature logic...
}
Best Practices
- Centralize configuration in the
config/directory. - Use environment variables for all secrets and environment-specific values.
- Validate configuration values before use.
- Document all required config options for new team members.