How to Create Custom Middleware in Laravel 11?

By Hardik Savani April 16, 2024 Category : Laravel

laravel 11 define middleware

Hello, In this post, I will teach you how to create custom middleware in laravel 11 framework.

The release of Laravel 11 is around the corner and it is packed with a lot of new features and improvements. Laravel 11 comes with a slimmer application skeleton. Laravel 11 introduce streamlined application structure, per-second rate limiting, health routing etc.

Laravel middleware is a mechanism that filters HTTP requests entering your application. It sits between the request and the application's core, allowing you to intercept, modify, or reject requests based on certain conditions. Middleware can be used for tasks like authentication, logging, and request manipulation. It provides a flexible way to handle cross-cutting concerns in your application's HTTP lifecycle, ensuring clean and modular code organization.

In Laravel 11, the method to register middleware has changed. Before Laravel 11, you could register your middleware in the `Kernel.php` file. But in Laravel 11, you need to define middleware in the `app.php` file. In this example, we'll create a "LogRequests" middleware to log request URLs. So, let's see the simple example step by step.

Step for Create Custom Middleware in Laravel 11

  • Step 1: Install Laravel 11
  • Step 2: Create Middleware
  • Step 3: Register Middleware
  • Step 4: Apply Middleware
  • Run Laravel App

Step 1: Install Laravel 11

This is optional; however, if you have not created the Laravel app, then you may go ahead and execute the command below:

composer create-project --prefer-dist laravel/laravel laravel-dev dev-master

Step 2: Create Middleware

In this step, we will create the "LogRequests" middleware and log the request URL.

php artisan make:middleware LogRequests

app/Http/Middleware/LogRequests.php

<?php
  
namespace App\Http\Middleware;
  
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
  
class LogRequests
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // Log the incoming request
        info('Incoming request: ' . $request->fullUrl());
  
        // Continue to the next middleware or controller
        return $next($request);
    }
}

Step 3: Register Middleware

In this step, we will simply register our custom middleware to `app.php` file as shown in the code below:

bootstrap/app.php

<?php
   
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
   
return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'logRequests' => \App\Http\Middleware\LogRequests::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Step 4: Apply Middleware

In this step, we will create two routes and apply the "logRequests" middleware. So, let's update the code.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
Route::middleware(['logRequests'])->group(function () {
    Route::get('/example', function () {
        return 'Example route';
    });
      
    Route::get('/example-2', function () {
        return 'Example route 2';
    });
});

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/example

http://localhost:8000/example-2

Output:


[2024-03-06 10:42:43] local.INFO: Incoming request: http://localhost:8000/example  
[2024-03-06 10:42:46] local.INFO: Incoming request: http://localhost:8000/example-2 

I hope it can help you...

Shares