A Detailed Guide to Installing and Configuring Laravel
Configuration is Laravel's "dashboard"—understanding the relationship between .env and config/ is like having access to a car's dashboard, allowing you to adjust engine parameters at any time.
1. What You'll Learn
.envEnvironment Files andconfig/*.phpConfiguration Loading Mechanism- Environment Switching: local/staging/production Configuration Policy
- Database Connection Configuration (MySQL & PostgreSQL)
- Cache and Session-Driven Configuration
php artisan config:cacheConfiguring the cache in the production environment
2. A True Story from the World of Operations
(1) Pain Point: Disorganized Development Environment Configuration
Alice used MySQL while developing ShopMetrics locally, but after deploying it to the staging server, she couldn't connect to the database—because she had hard-coded DB_PASSWORD into the code, and when she pushed it to Git, it was overwritten by her colleague Bob's local password. To make matters worse, Charlie accidentally committed the production environment's APP_DEBUG=true to the repository, exposing the entire error stack trace to users. It took the three of them two days to troubleshoot all the configuration issues.
(2) Solution for .env Configuration
Laravel uses .env files to isolate environment variables—one each for local, staging, and production—and never hard-codes sensitive values in the code.
# .env (local — never commit this file)
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=shopmetrics_local
DB_USERNAME=root
DB_PASSWORD=secret
APP_DEBUG=true
(3) Revenue
After Alice managed the configuration using .env, the local and production environments no longer interfere with each other, and APP_DEBUG automatically shuts down in the production environment, so Bob will never run into the password-overwrite issue again.
3. Environment Configuration Mechanism
Laravel's configuration system consists of two layers: the .env file stores environment variables, and the config/*.php file reads and organizes these variables.
graph TD
A[.env file] -->|dotenv loads| B[$_ENV / $_SERVER]
B -->|config reads| C[config/database.php]
C -->|env helper| D["env('DB_HOST', 'localhost')"]
D -->|fallback| E[Default value if not set]
(1) A Detailed Explanation of the .env File
.env Files are located in the project root directory and use the KEY=VALUE format; never commit them to Git.
| Rule | Description |
|---|---|
| Format | KEY=VALUE, no spaces on either side of the equals sign |
| Quotes | Use quotes for values containing spaces: APP_NAME="My App" |
| Comments | Lines beginning with # are comments |
| Type | All values are strings; you must manually convert the type in the code |
| Priority | Actual environment variable > .env file value |
(2) The config Directory Structure
config/ Returns a configuration array for each PHP file and reads environment variables using the env() function.
| Profile | Purpose |
|---|---|
app.php |
App Name, Time Zone, Encryption Key, Debug Mode |
database.php |
Database Connection, Table Name Migration |
cache.php |
Cache Drivers (file/redis/database) |
session.php |
Session Drivers and Lifecycle |
mail.php |
Email Service Configuration |
filesystems.php |
File Storage Driver |
(1) ▶ Example: Viewing the current configuration values
# Check a specific config value
php artisan tinker
# In tinker REPL:
config('app.name')
# => "Laravel"
config('database.default')
# => "mysql"
config('cache.default')
# => "file"
Output:
# Command executed successfully
4. Database Configuration
(1) MySQL Configuration
// config/database.php — 'mysql' connection
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'shopmetrics'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
],
(2) PostgreSQL Configuration
// config/database.php — 'pgsql' connection
'pgsql' => [
'driver' => 'pgsql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'shopmetrics'),
'username' => env('DB_USERNAME', 'postgres'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
],
| Dimension | MySQL | PostgreSQL |
|---|---|---|
| Default Port | 3306 | 5432 |
| JSON Support | Native in 5.7+ | Native and More Powerful |
| Full-Text Search | Basic | Advanced (tsvector) |
| Extensibility | Medium | High (PostGIS, etc.) |
| Use Cases | E-commerce/Content | Geography/Analytics |
(1) ▶ Example: Configuring the MySQL connection for ShopMetrics
# .env — Configure MySQL for ShopMetrics
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=shopmetrics
DB_USERNAME=shopmetrics_user
DB_PASSWORD=Str0ngP@ssw0rd!
# Create the database
mysql -u root -p -e "CREATE DATABASE shopmetrics;"
mysql -u root -p -e "CREATE USER 'shopmetrics_user'@'localhost' IDENTIFIED BY 'Str0ngP@ssw0rd!';"
mysql -u root -p -e "GRANT ALL PRIVILEGES ON shopmetrics.* TO 'shopmetrics_user'@'localhost';"
mysql -u root -p -e "FLUSH PRIVILEGES;"
# Test connection
php artisan db:show
# Database: shopmetrics | MySQL 8.x | Tables: 0
Output:
# Command executed successfully
5. Cache and Session Drivers
(1) Comparison of Cache Drivers
| Driver | Use Cases | Performance | Persistence |
|---|---|---|---|
file |
Development/Small Projects | Slow | ✅ |
database |
Without Redis | Medium | ✅ |
redis |
Production Environment | Fast | ✅ |
memcached |
High-concurrency reads | Fast | ❌ |
array |
Test | Extremely fast | ❌ |
(2) Comparison of Session Drivers
| Driver | Applicable Scenarios | Description |
|---|---|---|
file |
Development | Stored in storage/framework/sessions/ |
database |
Medium-sized | Requires creation of the "sessions" table |
redis |
Production | High performance, TTL support |
cookie |
Lightweight | Stored on the client after encryption, limited to 4KB |
array |
Test | Disappears when the request ends |
(1) ▶ Example: Configuring Redis Caching and Sessions
# .env — Configure Redis for cache and session
CACHE_DRIVER=redis
SESSION_DRIVER=redis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
# Install Redis PHP extension
pecl install redis
# Test Redis connection
php artisan tinker
# Cache::put('test_key', 'hello', 60)
# => true
# Cache::get('test_key')
# => "hello"
Output:
# Command executed successfully
6. Environment Switching Strategy
(1) Multi-Environment Configuration Solutions
| Solution | Approach | Pros and Cons |
|---|---|---|
| Multiple .env files | .env.local / .env.staging / .env.production |
Simple but requires manual switching |
| CI/CD Integration | Set environment variables in the deployment script | Secure but requires a CI platform |
| Laravel Envoyer | Server-side .env management | Official tool, but paid |
(2) Differences in Key Environmental Variables
| Variable | Local | Staging | Production |
|---|---|---|---|
APP_ENV |
local | staging | production |
APP_DEBUG |
true | true | false |
CACHE_DRIVER |
file | redis | redis |
SESSION_DRIVER |
file | redis | redis |
LOG_LEVEL |
debug | info | warning |
(1) ▶ Example: Preparing .env files for different environments
# .env.local (development)
APP_ENV=local
APP_DEBUG=true
DB_DATABASE=shopmetrics_dev
CACHE_DRIVER=file
LOG_LEVEL=debug
# .env.staging (staging server)
APP_ENV=staging
APP_DEBUG=true
DB_DATABASE=shopmetrics_staging
CACHE_DRIVER=redis
LOG_LEVEL=info
# .env.production (live server)
APP_ENV=production
APP_DEBUG=false
DB_DATABASE=shopmetrics
CACHE_DRIVER=redis
LOG_LEVEL=warning
Output:
# Command executed successfully
7. Configuring the Cache
In a production environment, Laravel can merge and cache all configuration files into a single PHP file, thereby avoiding the need to read .env and parse config/*.php with every request.
(1) ▶ Example: Using the configuration cache command
# Cache all config (production)
php artisan config:cache
# Configuration cached successfully!
# After caching, env() returns null — always use config()
# This is a common gotcha!
# Clear config cache
php artisan config:clear
# Configuration cache cleared!
# Check if config is cached
php artisan config:status
# Config is cached.
Output:
# Command executed successfully
config:cache, the env() function will return null in non-configuration files. Use env() only in config/*.php; use config() everywhere else.
| Command | Function | Use Case |
|---|---|---|
config:cache |
Cache Configuration | Production Deployment |
config:clear |
Clear Cache | After Modifying Settings |
config:show |
View Configuration Values | Debug |
env |
View .env values | During development |
8. Comprehensive Example: Complete Environment Configuration for ShopMetrics
// ============================================
// Comprehensive: ShopMetrics complete .env config
// Covers: app, database, cache, session, mail, logging
// ============================================
// .env file for ShopMetrics (local development)
/*
APP_NAME=ShopMetrics
APP_ENV=local
APP_KEY=base64:generated-key-here
APP_DEBUG=true
APP_URL=http://localhost:8000
LOG_CHANNEL=stack
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=shopmetrics
DB_USERNAME=shopmetrics_user
DB_PASSWORD=Str0ngP@ssw0rd!
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_CONNECTION=database
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=shopmetrics-uploads
*/
# After configuring .env, run these commands:
php artisan key:generate
php artisan config:clear
php artisan migrate
php artisan db:seed
php artisan serve
Output:
Application key set successfully.
Configuration cache cleared!
Info: Using MySQL database: shopmetrics
Migration table created successfully.
Starting Laravel development server: http://127.0.0.1:8000
❓ FAQ
config:cache, env() returns null when accessing non-configuration files; therefore, you should always use config().php artisan serve will automatically reload the changes, but php-fpm requires php artisan config:clear or a service restart. In production environments where config:cache has been run, the cache must be rebuilt.config:cache?php artisan config:cache to regenerate the cache. This will re-read .env and all config files and generate new cache files.📖 Summary
- Laravel configuration is organized into two layers: .env stores environment variables, and config/*.php organizes configuration values.
- Use
env()only in config files; useconfig()everywhere else. - MySQL is suitable for e-commerce scenarios, PostgreSQL is suitable for analytics scenarios, and SQLite is suitable for development
- Redis is recommended for production environments as a caching and session management solution
- APP_DEBUG must be set to false in a production environment
- config:cache improves performance, but after caching, env() no longer works outside of configuration files
📝 Exercises
-
Basic Exercise (⭐): Configure the ShopMetrics project to use a MySQL database. Modify the database connection information in the
.envfile, then runphp artisan migrateto verify that the connection is successful. -
Advanced Exercise (⭐⭐): Create two environment configuration files,
.env.localand.env.staging, using different database names and cache drivers, and write a script to quickly switch between environments. -
Challenge (⭐⭐⭐): Investigate the implementation principles of
config:cache(readIlluminate/Foundation/Console/ConfigCacheCommand.php), explain whyenv()becomes invalid after caching, and describe how to safely use configuration caching in a production environment.



