Vì sao tối ưu performance Laravel quan trọng?
Một ứng dụng Laravel chậm sẽ:
- Giảm trải nghiệm người dùng
- Tăng bounce rate
- Tốn tài nguyên server
- Ảnh hưởng SEO
Google đánh giá cao website load nhanh. Backend tối ưu là yếu tố nền tảng.
Tài liệu chính thức về deployment:
👉 https://laravel.com/docs/deployment
1️⃣ Bật Cache Production (Bước cơ bản nhưng nhiều người quên)
Laravel có nhiều cơ chế cache built-in.
Cache config
php artisan config:cache
Cache route
php artisan route:cache
Cache view
php artisan view:cache
Laravel docs về caching:
👉 https://laravel.com/docs/cache
2️⃣ Tối ưu Database Query
Database thường là bottleneck lớn nhất.
Kiểm tra query
Dùng:
- Laravel Debugbar (dev)
- Laravel Telescope
- Log query trong production
Ví dụ bật log query:
DB::listen(function ($query) {
logger($query->sql);
});
Tránh SELECT *
Sai:
User::all();
Đúng hơn:
User::select('id', 'name', 'email')->get();
Giảm data load → giảm memory → tăng tốc.
3️⃣ N+1 Query – Sát thủ performance
Sai:
$users = User::all();foreach ($users as $user) {
echo $user->orders;
}
Đây là N+1 problem.
Đúng:
$users = User::with('orders')->get();
Đọc thêm về eager loading:
👉 https://laravel.com/docs/eloquent-relationships
(Bài Eloquent sau sẽ đào sâu hơn.)
4️⃣ Sử dụng Queue Cho Task Nặng
Không nên:
- Gửi email trong request
- Call API ngoài trong request
- Resize ảnh trong request
Thay vào đó, dùng Queue:
php artisan queue:work
Ví dụ:
SendWelcomeEmail::dispatch($user);
Laravel queue documentation:
👉 https://laravel.com/docs/queues
Queue giúp:
✔ Giảm response time
✔ Xử lý background
✔ Scale tốt hơn
5️⃣ Cache Query Kết Quả
Ví dụ:
$users = Cache::remember('active_users', 3600, function () {
return User::where('active', 1)->get();
});
Phù hợp cho:
- Dashboard
- Static data
- Report
6️⃣ Sử dụng Index Database
Laravel không tự động tối ưu index cho bạn.
Ví dụ migration:
$table->index('email');
Index giúp:
- Tăng tốc WHERE
- Tăng tốc JOIN
- Giảm full table scan
Đọc thêm về database indexing:
👉 https://use-the-index-luke.com/
7️⃣ Singleton Cho Service Nặng
Nếu bạn resolve service nhiều lần:
$this->app->singleton(PaymentService::class);
Singleton giúp tránh khởi tạo nhiều lần.
8️⃣ Sử dụng Opcache & PHP-FPM Tối Ưu
Laravel performance phụ thuộc vào:
- PHP version
- Opcache
- Web server config
Khuyến nghị:
- PHP 8.2+
- Bật Opcache
- Sử dụng Nginx + PHP-FPM
PHP Opcache docs:
👉 https://www.php.net/manual/en/book.opcache.php
9️⃣ Horizon & Monitoring
Nếu dùng Redis queue, hãy dùng:
Laravel Horizon
Horizon giúp:
- Theo dõi job
- Giám sát worker
- Phát hiện lỗi
Monitoring là chìa khóa production.
Checklist Performance Laravel Production
- config:cache
- route:cache
- Không N+1 query
- Queue cho task nặng
- Database có index
- Monitoring hệ thống
Kết luận
Tối ưu performance Laravel không chỉ là:
- Cache
- Query
Mà còn là:
- Kiến trúc đúng
- Background job
- Monitoring
