404 Not Found

404 Not Found


nginx

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


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.

BASH
# .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.

100%
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

BASH
# Check a specific config value
php artisan tinker
# In tinker REPL:
config('app.name')
# => "Laravel"

config('database.default')
# => "mysql"

config('cache.default')
# => "file"

Output:

TEXT
# Command executed successfully

4. Database Configuration

(1) MySQL Configuration

PHP
// 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

PHP
// 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

BASH
# .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:

TEXT
# 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

BASH
# .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:

TEXT
# 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

BASH
# .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:

TEXT
# 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

BASH
# 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:

TEXT
# Command executed successfully
⚠️ Note: After executing 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

PHP
// ============================================
// 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
*/
BASH
# 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:

TEXT
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

Q What is the difference between env() and config()?
A env() directly reads environment variables from the .env file; config() reads configuration values organized in config/*.php files. In a production environment, after running config:cache, env() returns null when accessing non-configuration files; therefore, you should always use config().
Q Should the .env file be committed to Git?
A Absolutely not. The .env file contains sensitive information such as database passwords and API keys. Only commit .env.example as a template; the actual .env file should be created by operations on the server.
Q Do I need to restart the server after modifying .env?
A Yes. 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.
Q When should I use SQLite, and when should I use MySQL?
A Use SQLite for learning and prototyping (zero configuration); use MySQL for production environments (enterprise features such as concurrency, replication, and backup); choose PostgreSQL when advanced queries (full-text search, GIS) are required.
Q What is the purpose of APP_KEY?
A APP_KEY is used for all encryption operations (session encryption, password reset tokens, CSRF tokens, etc.). If you change the APP_KEY, all encrypted data will become undecipherable. Do not change it after deployment to a production environment.
Q How do changes to .env take effect after running config:cache?
A Simply run php artisan config:cache to regenerate the cache. This will re-read .env and all config files and generate new cache files.

📖 Summary


📝 Exercises

  1. Basic Exercise (⭐): Configure the ShopMetrics project to use a MySQL database. Modify the database connection information in the .env file, then run php artisan migrate to verify that the connection is successful.

  2. Advanced Exercise (⭐⭐): Create two environment configuration files, .env.local and .env.staging, using different database names and cache drivers, and write a script to quickly switch between environments.

  3. Challenge (⭐⭐⭐): Investigate the implementation principles of config:cache (read Illuminate/Foundation/Console/ConfigCacheCommand.php), explain why env() becomes invalid after caching, and describe how to safely use configuration caching in a production environment.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏