How to Create Custom Middleware In Laravel 11

  Mar 2024
  ITSolutionsGuides
  Category: Laravel
How to Create Custom Middleware In Laravel 11

Welcome To ITSolutionsGuides,


In this tutorial we will see how to create a custom middleware in the laravel 11 version which has different folder section than the previous laravel versions. Middlewares play a vital role in the laravel projects by filtering any incoming requests and perform certain actions like authentication, verifycsrftoken, encryption etc which elevates the security of the laravel application. In latest laravel version 11 the middleware sections are completely removed any the file in which we will register our middleware are also removed. Since the middlewares are important for the laravel application we need to know how to create a middleware in the laravel 11 version in order to provide the quality web applications. In previous laravel versions there were 10 default middlewares, but in the latest laravel 11 version the middleware sections are completely removed. Since we can able to create the middleware using the artisan command and use it in our laravel project. In previous versions of the laravel we need to register the middlewares in the app/Http/Kernel.php file but in latest laravel 11 version these file is also removed, So we need to register our middleware in the bootstrap/app.php file in laravel 11 version.

Let's Install Laravel Application

The latest version of laravel is laravel 11 which was released recently, lets install the laravel 11 project in the name of "laravel_latest_11" using the following artisan command

laravel new laravel_latest_11

Let's Create Middleware

In Laravel 11 the default middleware section were removed but we can create the middleware using the artisan command like any other laravel versions .detailed explanation about creating middleware using artisan command so lets create the middleware.

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);
    }
}

Let's Register the Middleware

In previous versions of the laravel we need to register the created middleware in the app/Http/Kernel.php file. But this file has been removed in the latest laravel 11 version, So we need to register our middleware in the bootstrap/app.php file.



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();

Let's Use Middleware In Routes

Lets use the middleware in the routes. It is same as that in the previous versions of the laravel.
Route::middleware([''])->group(function () {}


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';
    });
});

We hope it helps everyone. Thanks for supporting ITSolutionsGuides and keep supporting us also follow us in social media platforms.

Subscribe for NewsLetter

Be the first to know about releases and tutorial news and solutions.

We care about your data in our privacy policy.

ITSolutionsGuides

ITSolutionsGuides was started mainly to provide good and quality web solutions for all the developers. We provide tutorials to support all the developers and also we try to provide solutions to the errors we face while coding.

Contact US

ITSolutionsGuides, provide users with an easy-to-use form to reach out for support or inquiries.

whatsapp  gmail  instagram-new--v1  facebook-circled  twitter-circled  linkedin  github  pinterest 

Copyright © 2023 - 2024 All rights reserved | ITSolutionsGuides