Laravel Middleware Chi Tiet: Xac Thuc, Rate Limiting va Custom Middleware
Huong dan toan dien ve Laravel Middleware voi cac vi du thuc te ve xac thuc nguoi dung, rate limiting, tao middleware tuy chinh va cac pattern san xuat nang cao trong ung dung PHP.

Middleware trong Laravel dong vai tro nhu mot lop loc giua cac HTTP request den va logic xu ly cua ung dung. Moi request deu phai di qua mot chuoi cac lop middleware truoc khi toi duoc controller, va moi response cung di nguoc lai qua chinh chuoi do. Co che nay tuan theo pattern Chain of Responsibility -- mot kien truc cho phep tach biet cac moi quan tam xuyen suot nhu xac thuc, gioi han tan suat truy cap va kiem tra quyen han ra khoi logic nghiep vu chinh. Doi voi bat ky ung dung Laravel nao huong toi moi truong san xuat trong nam 2026, viec nam vung middleware pipeline la dieu khong the thieu.
Middleware chan cac HTTP request truoc khi chung toi duoc route. Laravel 12 dang ky toan bo middleware trong bootstrap/app.php thong qua fluent API. Cac middleware tich hop san xu ly xac thuc, bao ve CSRF, quan ly session va rate limiting ngay khi cai dat.
Co Che Hoat Dong Cua Middleware Pipeline Trong Laravel
Middleware pipeline trong Laravel co the hinh dung nhu nhieu lop vo dong tam. Moi HTTP request di tu ngoai vao trong, qua tung lop middleware cho den khi toi controller. Response sau do di nguoc lai qua cac lop do theo chieu nguoc lai. Moi middleware nhan request, thuc hien logic cua minh, roi chuyen request sang lop tiep theo thong qua $next($request) hoac cat ngang pipeline bang cach tra ve response truc tiep.
Vi du duoi day minh hoa mot middleware do thoi gian xu ly request. Doan code truoc loi goi $next($request) chay truoc khi request den controller. Doan code sau do chay sau khi response da duoc tao -- mot vi du dien hinh cho kien truc before/after cua middleware.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\Response;
class LogRequestTime
{
public function handle(Request $request, Closure $next): Response
{
$start = microtime(true); // Capture start time
$response = $next($request); // Pass to next middleware
$duration = microtime(true) - $start;
Log::info('Request completed', [
'url' => $request->url(),
'method' => $request->method(),
'duration' => round($duration * 1000, 2) . 'ms',
]);
return $response; // Return response up the stack
}
}Diem mau chot nam o $next($request): loi goi nay chuyen request sang middleware tiep theo trong chuoi. Tat ca code truoc loi goi nay la logic before-middleware, tat ca code sau do la logic after-middleware. Neu $next() khong bao gio duoc goi -- chang han khi kiem tra xac thuc that bai -- request se khong bao gio toi duoc controller.
Authentication Middleware: Bao Ve Route
Laravel cung cap san middleware auth, duoc anh xa toi Illuminate\Auth\Middleware\Authenticate. Khi ap dung middleware nay cho mot route, chi nhung nguoi dung da xac thuc moi co the truy cap. Nguoi dung chua xac thuc se nhan response 401 (doi voi API) hoac duoc chuyen huong toi trang dang nhap (doi voi web).
Cac route co the duoc bao ve rieng le hoac theo nhom. Viec nhom cac route lai la phuong phap duoc uu tien vi giup dinh nghia route gon gang hon va dam bao khong co route nao bi bo sot bao ve.
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\ProfileController;
// Single route protection
Route::get('/dashboard', [DashboardController::class, 'index'])
->middleware('auth');
// Group protection for multiple routes
Route::middleware('auth')->group(function () {
Route::get('/profile', [ProfileController::class, 'show']);
Route::put('/profile', [ProfileController::class, 'update']);
Route::delete('/profile', [ProfileController::class, 'destroy']);
});Xac Thuc Da Guard
Cac ung dung co nhieu loai nguoi dung -- panel quan tri, khu vuc khach hang, API -- can su dung xac thuc dua tren guard. Middleware auth chap nhan tham so guard de chi dinh driver xac thuc nao se duoc su dung. Dieu nay cho phep tach biet hoan toan co che xac thuc giua cac phan khac nhau cua ung dung.
// API routes use the 'sanctum' guard
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', fn (Request $request) => $request->user());
Route::apiResource('/orders', OrderController::class);
});
// routes/web.php
// Admin routes use a custom 'admin' guard
Route::middleware('auth:admin')->prefix('admin')->group(function () {
Route::get('/dashboard', [AdminController::class, 'index']);
Route::get('/users', [AdminController::class, 'users']);
});Tham so guard sau dau hai cham cho Laravel biet cau hinh xac thuc nao can kiem tra. Moi guard co the su dung user model, provider va driver rieng, tao nen mot kien truc linh hoat cho cac ung dung phuc tap.
Middleware guest la nghich dao cua auth -- chi cho phep nguoi dung chua xac thuc di qua. Ap dung middleware nay cho cac route dang nhap va dang ky giup ngan nguoi dung da xac thuc truy cap lai nhung trang do. Cach su dung tuong tu: Route::middleware('guest')->get('/login', ...).
Rate Limiting Voi Throttle Middleware
Rate limiting bao ve ung dung khoi su lam dung, tan cong brute-force va qua tai khong mong muon. Middleware throttle trong Laravel gioi han so luong request ma mot client co the gui trong mot khoang thoi gian nhat dinh. Khi vuot qua gioi han, Laravel tu dong tra ve HTTP status code 429 (Too Many Requests).
Dang don gian nhat cua cau hinh duoc thuc hien truc tiep trong dinh nghia route. Tham so dau tien la so luong request toi da, tham so thu hai la khoang thoi gian tinh bang phut.
// Allow 60 requests per minute per user
Route::middleware('throttle:60,1')->group(function () {
Route::get('/posts', [PostController::class, 'index']);
Route::get('/posts/{post}', [PostController::class, 'show']);
});
// Stricter limit for write operations
Route::middleware(['auth:sanctum', 'throttle:10,1'])->group(function () {
Route::post('/posts', [PostController::class, 'store']);
Route::put('/posts/{post}', [PostController::class, 'update']);
});Named Rate Limiters Cho Kiem Soat Nang Cao
Viec dinh nghia named rate limiters trong AppServiceProvider mang lai kha nang kiem soat chi tiet dua tren ngu canh nguoi dung. Cach tiep can nay linh hoat hon nhieu so voi viec truyen tham so throttle truc tiep. Vi du duoi day the hien mot he thong phan tang: nguoi dung enterprise nhan gioi han rong rai hon, nguoi dung da xac thuc nhan gioi han vua phai, va cac truy cap an danh bi han che nghiem ngat nhat.
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Http\Request;
public function boot(): void
{
// API rate limiter with tiered access
RateLimiter::for('api', function (Request $request) {
$user = $request->user();
if ($user?->hasSubscription('enterprise')) {
return Limit::perMinute(500)->by($user->id); // Enterprise: 500/min
}
if ($user) {
return Limit::perMinute(100)->by($user->id); // Authenticated: 100/min
}
return Limit::perMinute(20)->by($request->ip()); // Anonymous: 20/min
});
// Login limiter to prevent brute force
RateLimiter::for('login', function (Request $request) {
return Limit::perMinute(5)
->by($request->ip()) // Key by IP address
->response(function () { // Custom exceeded response
return response()->json([
'message' => 'Too many login attempts. Try again in a minute.',
], 429);
});
});
}Cac named limiter duoc ap dung cho route thong qua cu phap throttle:name, thay vi truyen truc tiep cac gia tri so.
Route::middleware('throttle:api')->group(function () {
Route::apiResource('/posts', PostController::class);
});
// routes/web.php
Route::middleware('throttle:login')
->post('/login', [AuthController::class, 'login']);Uu diem cua cach tiep can nay nam o viec cau hinh tap trung: khi gioi han duoc dieu chinh, hanh vi cua tat ca route su dung limiter tuong ung se tu dong thay doi. Phuong thuc by() xac dinh cach nhom cac request lai -- theo user ID cho nguoi dung da xac thuc va theo dia chi IP lam phuong an du phong.
Sẵn sàng chinh phục phỏng vấn Laravel?
Luyện tập với mô phỏng tương tác, flashcards và bài kiểm tra kỹ thuật.
Xay Dung Custom Middleware Tu Dau
Khi cac middleware tich hop san khong dap ung du yeu cau, Laravel cho phep tao middleware tuy chinh bang mot lenh Artisan duy nhat.
php artisan make:middleware EnsureUserHasRoleLenh nay tao mot class trong thu muc app/Http/Middleware/ voi phuong thuc handle da duoc chuan bi san. Sau do, logic mong muon co the duoc trien khai ngay trong phuong thuc nay.
Middleware Kiem Soat Truy Cap Theo Vai Tro
Mot pattern pho bien cho custom middleware la kiem soat quyen truy cap dua tren vai tro (role-based authorization). Middleware duoi day kiem tra xem nguoi dung da xac thuc co so huu mot trong cac vai tro yeu cau hay khong. Toan tu spread (...$roles) cho phep truyen nhieu vai tro lam tham so.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureUserHasRole
{
public function handle(Request $request, Closure $next, string ...$roles): Response
{
$user = $request->user();
if (! $user || ! $user->hasAnyRole($roles)) {
abort(403, 'Insufficient permissions.');
}
return $next($request);
}
}Viec dang ky duoc thuc hien bang alias trong bootstrap/app.php, cho phep su dung middleware trong dinh nghia route thong qua mot ten ngan gon. Cac tham so duoc truyen sau dau hai cham, nhieu tham so cach nhau bang dau phay.
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'role' => \App\Http\Middleware\EnsureUserHasRole::class,
]);
})
// routes/web.php
Route::middleware('role:admin')->group(function () {
Route::get('/admin', [AdminController::class, 'index']);
});
// Multiple roles: admin OR editor can access
Route::middleware('role:admin,editor')->group(function () {
Route::resource('/articles', ArticleController::class);
});Middleware Bien Doi Request
Middleware co the thay doi request truoc khi no toi controller. Mot middleware cho JSON API kiem tra content type header va lam sach cac chuoi dau vao bang cach loai bo khoang trang thua:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class ApiRequestSanitizer
{
public function handle(Request $request, Closure $next): Response
{
// Reject non-JSON requests on API routes
if (! $request->expectsJson() && $request->isMethod('POST')) {
return response()->json(
['error' => 'Content-Type must be application/json'],
415
);
}
// Trim all string inputs
$input = $request->all();
array_walk_recursive($input, function (&$value) {
if (is_string($value)) {
$value = trim($value);
}
});
$request->merge($input);
return $next($request);
}
}Middleware nay xu ly hai van de cung luc: kiem tra content type cho cac POST request va lam sach tat ca dau vao dang chuoi bang cach trim khoang trang. Nen dat middleware nay o dau nhom API middleware de cac middleware va controller phia sau nhan duoc du lieu da duoc lam sach.
Dang Ky Middleware Trong Laravel 12
Tu Laravel 11 tro di, toan bo cau hinh middleware duoc tap trung trong bootstrap/app.php, thay the cho cach tiep can cu hon su dung app/Http/Kernel.php. Tai day co the dinh nghia middleware toan cuc, middleware nhom, alias va thu tu uu tien thuc thi.
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withMiddleware(function (Middleware $middleware) {
// Global middleware (runs on every request)
$middleware->append(
\App\Http\Middleware\LogRequestTime::class
);
// Add to the 'web' middleware group
$middleware->web(append: [
\App\Http\Middleware\TrackPageViews::class,
]);
// Add to the 'api' middleware group
$middleware->api(prepend: [
\App\Http\Middleware\ApiRequestSanitizer::class,
]);
// Register aliases for route-level use
$middleware->alias([
'role' => \App\Http\Middleware\EnsureUserHasRole::class,
'subscribed' => \App\Http\Middleware\EnsureUserIsSubscribed::class,
]);
// Control execution order
$middleware->priority([
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Auth\Middleware\Authenticate::class,
\App\Http\Middleware\EnsureUserHasRole::class,
]);
})
->create();Mang priority co vai tro quan trong khi nhieu middleware duoc gan cho cung mot route. Laravel sap xep chung theo danh sach nay, dam bao session duoc khoi tao truoc khi xac thuc chay, va xac thuc hoan tat truoc khi kiem tra vai tro. Cac phuong thuc append() va prepend() kiem soat vi tri chen middleware -- o cuoi hoac o dau mot nhom.
Middleware chay theo thu tu duoc dang ky. Doi voi middleware cap route, mang priority ghi de thu tu mac dinh. Luon dat authentication middleware truoc authorization middleware de tranh kiem tra vai tro tren cac request chua xac thuc.
Terminable Middleware Cho Tac Vu Sau Response
Khong phai tat ca tac vu deu can hoan thanh truoc khi response duoc gui toi client. Terminable middleware thuc thi logic sau khi response da duoc gui di hoan toan. Day la giai phap ly tuong cho cac tac vu nhu ghi log, thu thap analytics hoac don dep tai nguyen ma khong lam cham trai nghiem nguoi dung.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;
class CollectAnalytics
{
public function handle(Request $request, Closure $next): Response
{
return $next($request); // Pass through without delay
}
public function terminate(Request $request, Response $response): void
{
// Runs after response is sent to client
DB::table('analytics')->insert([
'path' => $request->path(),
'method' => $request->method(),
'status_code' => $response->getStatusCode(),
'user_id' => $request->user()?->id,
'ip' => $request->ip(),
'created_at' => now(),
]);
}
}Phuong thuc terminate nhan ca request goc va response cuoi cung. Can dang ky middleware nay dang singleton trong AppServiceProvider de dam bao cung mot instance xu ly ca handle() va terminate().
Cac Pattern Middleware Thuc Te Cho Moi Truong San Xuat
Mot so pattern middleware xuat hien lien tuc trong cac ung dung Laravel o moi truong san xuat.
Bo qua che do bao tri -- cho phep cac IP noi bo truy cap ung dung trong thoi gian bao tri:
class MaintenanceBypass
{
private array $allowedIps = ['192.168.1.0/24', '10.0.0.1'];
public function handle(Request $request, Closure $next): Response
{
if (app()->isDownForMaintenance()) {
foreach ($this->allowedIps as $ip) {
if ($request->ip() === $ip) {
return $next($request);
}
}
}
return $next($request);
}
}Security headers -- them HSTS, content security policy va cac header bao mat khac vao moi response:
class SecurityHeaders
{
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('X-Frame-Options', 'SAMEORIGIN');
$response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
$response->headers->set(
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains'
);
return $response;
}
}Ca hai pattern nay minh hoa hai vi tri middleware chinh: truoc request (maintenance bypass kiem tra IP va co the chan truy cap) va sau response (security headers thay doi response truoc khi gui di). Day la nhung middleware nen duoc dang ky dang global vi can ap dung cho moi request.
Sẵn sàng chinh phục phỏng vấn Laravel?
Luyện tập với mô phỏng tương tác, flashcards và bài kiểm tra kỹ thuật.
Ket Luan
- Laravel middleware hoat dong nhu mot pipeline: moi class xu ly request, tac dong len no, roi chuyen tiep hoac cat ngang bang mot response
- Middleware
authbao ve route bang xac thuc dua tren guard, ho tro nhieu loai nguoi dung thong qua cu phapauth:guard - Rate limiting thong qua middleware
throttleva dinh nghiaRateLimiter::for()cho phep kiem soat truy cap phan tang dua tren ngu canh nguoi dung - Custom middleware xu ly cac moi quan tam xuyen suot nhu kiem tra vai tro, lam sach request va security headers ma khong lam roi controller
- Toan bo dang ky middleware trong Laravel 12 dien ra tai
bootstrap/app.phpsu dung fluent API, voiprioritykiem soat thu tu thuc thi - Terminable middleware chay cac tac vu sau response (analytics, logging) ma khong anh huong toi do tre phia nguoi dung
- Tham so middleware qua cu phap
:paramgiu cho dinh nghia route ro rang va cac class middleware co the tai su dung trong nhieu ngu canh khac nhau
Bắt đầu luyện tập!
Kiểm tra kiến thức với mô phỏng phỏng vấn và bài kiểm tra kỹ thuật.
Thẻ
Chia sẻ
Bài viết liên quan

Cau Hoi Phong Van Laravel va PHP: Top 25 Nam 2026
25 cau hoi phong van Laravel va PHP thuong gap nhat. Service Container, Eloquent ORM, middleware, queues va trien khai production voi dap an chi tiet kem code mau.

Laravel 11: Xây dựng Ứng dụng Hoàn chỉnh từ Đầu
Hướng dẫn toàn diện xây dựng ứng dụng Laravel 11 với xác thực, REST API, Eloquent ORM và triển khai. Bài hướng dẫn thực hành dành cho lập trình viên từ cơ bản đến trung cấp.

Symfony 7: API Platform va Cac Thuc Hanh Tot Nhat
Huong dan day du ve API Platform 4 voi Symfony 7. Tu State Processors, State Providers den bao mat va kiem thu — tat ca thuc hanh tot nhat cho REST API san xuat.