How to Create Custom Middleware in Laravel 11

How to Create Custom Middleware in Laravel 11

Middleware is an essential component of Laravel applications, acting as a strong mediator between incoming HTTP requests and your application's core logic. It allows developers to perform particular actions before a request reaches its destination, making operations like authentication, authorization, request manipulation, and response formatting more efficient. The tutorial below delves deeply into the creation and implementation of custom middleware in Laravel 11, allowing you to improve the security, flexibility, and maintainability of your application.

Crafting Custom Middleware in Laravel 11: A Step-by-Step Guide

1. Generating the Middleware Class:

Utilize Laravel's Artisan command-line tool to streamline the creation process:

php artisan make:middleware ValidToken

This command generates a new class named ValidToken.php within the app/Http/Middleware directory, serving as the foundation for your custom middleware's functionality.

2. Implementing the Middleware Logic:

Open the newly created ValidToken.php class and define the handle method, which constitutes the core of your middleware's behavior.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class ValidToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->header('X-API-Token'); // Replace with your token retrieval method

        if (!$token || $token !== config('app.api_token')) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }

        return $next($request);
    }
}

In this example, the handle method retrieves the API token from the request header and compares it to the value stored in your application's configuration (config('app.api_token')). If the token matches, the request proceeds to the intended route ($next($request)); otherwise, an unauthorized response (401 status code) is returned.

3. Registering the Middleware:

To make your custom middleware operational, integrate it into Laravel's middleware stack. There are two primary approaches:

3.a) Global Middleware Registration:

Navigate to the app/Http/Kernel.php file and within the $middleware property, append your middleware class:

protected $middleware = [
    // ... other middleware
    \App\Http\Middleware\ValidToken::class,
];

3.b) Route-Specific Middleware Registration:

Using Route Closures:

Route::get('/protected-route', function () {
    // Route logic
})->middleware('ValidToken');

Using Route Group with Middleware:

Route::group(['middleware' => 'ValidToken'], function () {
    Route::get('/protected-route-1', function () {
        // Route logic
    });

    Route::get('/protected-route-2', function () {
        // Route logic
    });
});

By following these instructions, you can smoothly integrate custom middleware into your Laravel 11 application, opening up a plethora of options for improving security, flexibility, and maintainability.


  • Date: