Laravel 允許執行時動態修改配置,適用於多租戶、A/B 測試、環境切換場景:
<?php
// 動態設定快取驅動
Config::set('cache.default', 'redis');
var_dump(Config::get('cache.default')); // "redis"
Config::set('cache.default', 'memcached');
var_dump(Config::get('cache.default')); // "memcached"
// 實際使用(會讀取最新配置)
Cache::put('key', 'value', 60); // 寫入當前設定的驅動
Cache::get('key');
?>
注意: 動態配置僅影響當前請求生命週期,不會寫回 .env 或配置檔。
use 別名等價<?php
// 以下三種寫法效果相同:
// 1. 完整命名空間
\Cache::put('key', 'value');
// 2. 頂層 \ 別名(Laravel 註冊於根命名空間)
Cache::put('key', 'value');
// 3. use 導入
use Illuminate\Support\Facades\Cache;
Cache::put('key', 'value');
?>
原理:Laravel AliasLoader 將所有 Facade 註冊為根命名空間類別別名,\Cache 直接解析至 Illuminate\Support\Facades\Cache。
常見錯誤:Unable to create directory、Permission denied
# 1. 設定擁有者為 Web 伺服器使用者(以 nginx 為例)
chown -R www:www storage bootstrap/cache
# 2. 設定目錄權限(目錄 775,檔案 664)
find storage -type d -exec chmod 775 {} \;
find storage -type f -exec chmod 664 {} \;
find bootstrap/cache -type d -exec chmod 775 {} \;
find bootstrap/cache -type f -exec chmod 664 {} \;
# 3. 如果使用 ACL(更精細控制)
setfacl -R -m u:www:rwx storage bootstrap/cache
setfacl -R -d -m u:www:rwx storage bootstrap/cache
# 4. 清除配置/路由/視圖快取(部署後必做)
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan cache:clear
#!/bin/bash # deploy.sh 片段 # 權限修正 chown -R www-data:www-data /var/www/html/storage /var/www/html/bootstrap/cache chmod -R 775 /var/www/html/storage /var/www/html/bootstrap/cache # Composer 優化安裝 composer install --optimize-autoloader --no-dev # Laravel 優化 php artisan config:cache php artisan route:cache php artisan view:cache # Queue worker 重啟(如果使用 supervisor) supervisorctl restart laravel-worker:*
| 需求 | 解法 |
|---|---|
| 取得原始 SQL | DB::enableQueryLog(); ...; dd(DB::getQueryLog()) |
| 模型觀察器 | 定義 Observers 類,User::observe(UserObserver::class) |
| API 資源轉換 | php artisan make:resource UserResource,回傳 UserResource::collection($users) |
| 任務排程 | Kernel.php 的 schedule(),* * * * * php artisan schedule:run |
| 測試資料填充 | php artisan make:seeder UsersTableSeeder,factory(User::class, 50)->create() |
Laravel 5 系列雖已進入維護模式(L5.8 為最後版本),但核心概念(服務容器、Facades、Contracts、Eloquent)在 Laravel 6/7/8/9/10/11 中延續,掌握基礎機制有助於版本升級與深度除錯。