• Fri, Mar 2026

Laravel Middleware Explained: Securing and Filtering Your Web Requests

Laravel Middleware Explained: Securing and Filtering Your Web Requests

his detailed tutorial explores Laravel Middleware in depth. You’ll learn how middleware works, how to create and register your own, and how to use it to secure and filter user requests in your application. With step-by-step code examples, best practices, and visuals, this article will make you confident in mastering middleware for real-world projects.

Introduction

Imagine you are at the entrance of a secure building. A guard stands at the gate, checking whether you’re allowed to enter. If you have the right badge, you pass; if not, you’re turned away. In Laravel, that “guard” is middleware.

Middleware acts as a filter between the incoming HTTP request and your application’s response. It inspects, modifies, or blocks requests before they reach your controllers. Laravel provides many built-in middleware, and you can create your own for custom logic.

Why Middleware Matters

Middleware is essential for modern web applications. It allows developers to implement common functionality across multiple routes in a clean, reusable way. Here’s why middleware is important:

  • Security: Restrict access to authenticated users only.
  • Filtering: Sanitize input or block malicious requests.
  • Performance: Apply caching strategies at request level.
  • Consistency: Apply the same logic across multiple routes easily.

How Middleware Works in Laravel

Every HTTP request goes through a pipeline of middleware before it reaches the controller. Middleware can either allow the request to continue or stop it and return a response.


// Example of middleware pipeline
public function handle($request, Closure $next)
{
    // Perform some action before controller
    if ($request->ip() == '123.45.67.89') {
        return response('Blocked IP', 403);
    }

    return $next($request); // Pass to next middleware/controller
}
    

Built-in Middleware in Laravel

Laravel comes with several middleware by default. Here are the most commonly used ones:

MiddlewareDescription
authEnsures user is authenticated.
guestRedirects authenticated users away from guest-only pages.
verifiedEnsures the user has verified their email address.
throttleLimits number of requests per user within a time period.
csrfProtects against Cross-Site Request Forgery attacks.

Creating Custom Middleware

Step 1: Generate Middleware

php artisan make:middleware CheckAge

Step 2: Define Middleware Logic


// app/Http/Middleware/CheckAge.php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckAge
{
    public function handle(Request $request, Closure $next)
    {
        if ($request->age < 18) {
            return response('You are not allowed!', 403);
        }
        return $next($request);
    }
}
    

Step 3: Register Middleware

You can register middleware globally, in groups, or on specific routes.


// app/Http/Kernel.php
protected $routeMiddleware = [
    'check.age' => \App\Http\Middleware\CheckAge::class,
];
    

Step 4: Apply Middleware to Routes


// routes/web.php
Route::get('/restricted', function () {
    return "Welcome to restricted area!";
})->middleware('check.age');
    

Global vs Route Middleware

You can choose how to apply middleware:

  • Global Middleware: Runs for every request (e.g., maintenance mode).
  • Route Middleware: Applied only to specific routes.
  • Middleware Groups: Grouped for common tasks like “web” or “api”.

Middleware Groups Example


// app/Http/Kernel.php
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],
];
    

Using Parameters in Middleware

Middleware can also accept parameters. For example, a throttle middleware:


// routes/web.php
Route::get('/dashboard', function () {
    return 'Dashboard';
})->middleware('throttle:10,1');
    

This limits users to 10 requests per minute.

Practical Examples

Example 1: IP Blocking Middleware


class BlockIP
{
    public function handle($request, Closure $next)
    {
        $blockedIps = ['123.45.67.89'];

        if (in_array($request->ip(), $blockedIps)) {
            return response('Your IP is blocked', 403);
        }

        return $next($request);
    }
}
    

Example 2: Role-Based Middleware


class RoleMiddleware
{
    public function handle($request, Closure $next, $role)
    {
        if (! $request->user() || $request->user()->role !== $role) {
            abort(403, 'Unauthorized');
        }
        return $next($request);
    }
}
    

// routes/web.php
Route::get('/admin', function () {
    return 'Admin Dashboard';
})->middleware('role:admin');
    

Middleware Flow Diagram

Here’s a simple visual to explain how middleware works in Laravel:

Testing Middleware

You can test middleware with Laravel’s HTTP testing tools:


// tests/Feature/MiddlewareTest.php
public function test_blocked_ip_cannot_access()
{
    $response = $this->withServerVariables(['REMOTE_ADDR' => '123.45.67.89'])
                     ->get('/restricted');
    $response->assertStatus(403);
}
    

Best Practices for Middleware

  • Keep middleware focused on a single task.
  • Use middleware groups for common web or API tasks.
  • Always return meaningful error messages.
  • Do not overload middleware with business logic.
  • Test middleware thoroughly for edge cases.

Conclusion

Middleware is one of the most powerful features in Laravel. It acts as the gatekeeper for every request, giving you full control to secure and filter incoming data. Whether you’re implementing authentication, restricting access, logging activity, or filtering requests, middleware provides a clean, reusable solution. By mastering middleware, you’ll write cleaner, more secure, and more maintainable Laravel applications.

This website uses cookies to enhance your browsing experience. By continuing to use this site, you consent to the use of cookies. Please review our Privacy Policy for more information on how we handle your data. Cookie Policy