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.
- Author: Ahmed Bouchefra Follow @ahmedbouchefra
-
Date:
Related posts
How to use new Dumpable Trait in Laravel 11 Creating Custom Validation Rules in Laravel 11 How to Create Custom Middleware in Laravel 11 How to Create Custom Middleware in Laravel 11 How to Install Laravel 11 Application How to Create Routes in Laravel 10 How to Generate App Key in Laravel 11? How to Add Bootstrap 5 to Laravel 11 Build an app with Laravel 11 and MySQL Livewire 3 refresh component Building a RESTful API CRUD Application with Laravel 11 Should I use Livewire in Laravel? Laravel 11 new features & release date Laravel 10 CRUD Tutorial Laravel 10 CORS Explained in Detail Laravel 7/6 Auth Tutorial: Login/Register/Password Reset Example PHP Laravel 7/6 Tutorial: CRUD Example App with Bootstrap 4 and MySQL Database Laravel 7/6 Database Migrations Tutorial with Admin Roles Example Laravel 7/6 Email Verification Tutorial and Example Laravel 7/6 REST API CRUD Tutorial - Build a CRM [PART 2]: Eloquent Models and Relationships Laravel 6/7 Tutorial & New Features - Creating and Migrating a MySQL Database Laravel 7/6 CORS Tutorial and Example How to Install Vue.JS in Laravel 7/6 By Example How to Install Laravel 7 On Ubuntu, Windows and macOS How to Install Bootstrap 4 in Laravel 7/6 Tutorial and Example