Abdulhamed Zaghoul
Laravel Abdulhamed Zaghoul Dec 07, 2025 90 views 0 comments

Middleware in Laravel - Revolutionizing Request Handling

Middleware is a software layer that sits between the Request and Response, allowing you to inspect and modify both requests and responses in your application. In Laravel, Middleware is one of the most powerful tools that makes HTTP handling smooth and efficient.

1. Introduction: What Is Middleware?

Middleware is a filtering layer that sits between the HTTP Request and the Response. It allows you to inspect, modify, allow, or block requests before they reach your application logic.

In Laravel, Middleware is one of the most powerful features that makes request handling clean, reusable, and maintainable.

2. Native PHP vs. Laravel Middleware

2.1 How Request Handling Worked in Native PHP

Before frameworks, developers had to manually repeat login checks, CSRF validation, and sanitization on every page:

<?php session_start(); // Authentication if(!isset($_SESSION['user_id'])) { header('Location: login.php'); exit(); } // CSRF protection if($_SERVER['REQUEST_METHOD'] === 'POST') { if(!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) { die('Invalid CSRF token'); } } // Sanitization $username = htmlspecialchars($_POST['username']); $password = $_POST['password']; echo "Welcome user!"; ?>

Problems With Native PHP Approach

  • Repeated code across pages

  • Hard to maintain

  • Easy to forget critical checks

  • No unified request pipeline

3. Laravel Middleware: The Modern Solution

Key Advantages

  • Code reusability

  • Separation of concerns

  • Maintainability

  • Can be chained

  • Easy to test

  • Works globally or on specific routes

4. Core Use Cases with Real Examples

4.1 Authentication Verification

Create Middleware:

php artisan make:middleware CheckUserRole

Middleware Code:

namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class CheckUserRole { public function handle(Request $request, Closure $next, $role) { if (!Auth::check()) { return redirect('/login'); } if (Auth::user()->role !== $role) { abort(403, 'Unauthorized access'); } return $next($request); } }

Register in Kernel:

protected $routeMiddleware = [ 'role' => \App\Http\Middleware\CheckUserRole::class, ];

Usage:

Route::get('/admin/dashboard', function () { return view('admin.dashboard'); })->middleware(['auth', 'role:admin']);

4.2 CORS Handling

class CorsMiddleware { public function handle(Request $request, Closure $next) { $response = $next($request); $response->headers->set('Access-Control-Allow-Origin', '*'); $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization'); if ($request->getMethod() === 'OPTIONS') { return response()->json([], 200); } return $response; } }

4.3 Request Logging

class RequestLogger { public function handle(Request $request, Closure $next) { \Log::info('Request Started', [ 'method' => $request->method(), 'url' => $request->fullUrl(), 'ip' => $request->ip() ]); $response = $next($request); \Log::info('Request Completed', [ 'status' => $response->status() ]); return $response; } }

4.4 Localization Middleware

class Localization { public function handle(Request $request, Closure $next) { if(session()->has('locale')) { app()->setLocale(session()->get('locale')); } elseif($request->hasHeader('Accept-Language')) { app()->setLocale($request->header('Accept-Language')); } return $next($request); } }

4.5 Performance Optimization (Response Caching)

class CacheResponse { public function handle(Request $request, Closure $next, $minutes = 60) { $key = 'response_' . md5($request->fullUrl()); if(Cache::has($key) && $request->method() === 'GET') { return response(Cache::get($key)); } $response = $next($request); if($response->status() === 200 && $request->method() === 'GET') { Cache::put($key, $response->getContent(), now()->addMinutes($minutes)); } return $response; } }

5. Types of Middleware in Laravel

5.1 Global Middleware

Runs on every request:

protected $middleware = [ \App\Http\Middleware\TrustProxies::class, \App\Http\Middleware\CorsMiddleware::class, ];

5.2 Route Middleware

Used only for specific routes:

Route::middleware(['auth'])->group(function () { Route::get('/dashboard', 'DashboardController@index'); });

5.3 Middleware Groups

protected $middlewareGroups = [ 'web' => [ \Illuminate\Session\Middleware\StartSession::class, ], 'api' => [ 'throttle:60,1', ], ];

6. Advanced Examples


6.1 Device Type Detection

class CheckDeviceType { public function handle(Request $request, Closure $next, $device) { $agent = new \Jenssegers\Agent\Agent(); $match = match($device) { 'mobile' => $agent->isMobile(), 'tablet' => $agent->isTablet(), 'desktop' => $agent->isDesktop(), default => false, }; if(!$match) { return redirect()->route('unsupported.device'); } return $next($request); } }

6.2 Subscription Verification

class CheckSubscription { public function handle(Request $request, Closure $next, $plan = null) { $user = $request->user(); if(!$user->subscription || $user->subscription->expires_at->isPast()) { return redirect()->route('subscription.expired'); } if($plan && $user->subscription->plan !== $plan) { return redirect()->route('upgrade.plan'); } return $next($request); } }

6.3 Middleware With Multiple Parameters

public function handle(Request $request, Closure $next, ...$roles) { if(!in_array($request->user()->role, $roles)) { abort(403, 'Access denied'); } return $next($request); }

Usage:

Route::middleware('role:admin,manager')->get('/management', function () {});

7. Best Practices

Do

  • Keep middleware focused on one task

  • Use dependency injection

  • Handle errors properly

  • Maintain clear naming

  • Test middleware individually

Don’t

  • Put business logic in middleware

  • Make middleware very large

  • Overuse middleware when events or policies make more sense

8. Final Comparison

CriteriaNative PHPLaravel Middleware
ReusabilityLowVery High
MaintainabilityLowVery High
TestingHardEasy
PerformanceGoodVery Good
FlexibilityLowVery High
Separation of ConcernsWeakExcellent

9. Conclusion

Middleware in Laravel is not just a tool; it is a complete architectural pattern that enables:

  • Clean code with no repetition

  • Better performance and scalability

  • Centralized handling of authentication, caching, logging, and more

  • Modern, professional web application structure

Old Native PHP:

if(!isset($_SESSION['user'])) { header('Location: login.php'); exit(); }

Laravel Approach:

Route::middleware('auth')->group(function () { // Protected routes here });

Middleware is one of the reasons Laravel applications remain clean, elegant, and scalable.

Keywords:
Laravel Middleware PHP Middleware Laravel Authentication HTTP Middleware Web Development

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment

Configuration

COLORS