How to create and register a middleware in a Laravel 11 application

How to create and register a middleware in a Laravel 11 application

A Step-by-Step Guide to Enhancing Request Handling in Laravel 11

Featured on Hashnode

Introduction

Middleware contains defined conditions to be fulfilled by a request via any of the HTTP verbs before granting or rejecting access to response or specific part of an application. Middleware acts like a layer that filters request into the application and route them as defined. For example, a middleware can be used to check if a user making request to view profile details is authenticated or authorized to decide what action or logic to perform.

Will explain further when there’s a middleware.

How to create a Middleware

Middleware in Laravel can be created manually or via the command line interface.

Head over to the terminal and run the command to create a middleware.

php artisan make:middleware CheckRole
//CheckRole is the name of the middleware in this use case

This will create a middleware file in the app/Http/Middleware directory. Open this file and define the logic inside the handle method. For example, the middleware below basically checks if a user has an admin role or not.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class CheckRole
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next) : Response
    {
       if($request->has('role') && $request->role == 'admin'){
            return response('The user role of the incoming request is '. $request->role);
        }
        return $next($request);
    }
}

This could be used to check if an authenticated user have a role, or other conditions depending on the functionality or business needs of the application.

💡
The check can be performed before or after the request

Before the Request get’s into the application:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckRole
{
    public function handle(Request $request, Closure $next): Response
    {
        // Perform action | logics here

        return $next($request);
    }
}

After the response to the request:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class CheckRole
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        // Perform action | logics here

        return $response;
    }
}
💡
You can click the link below to watch the video on my Youtube channel

Registering a Middleware in Laravel 11

In Laravel 11 middleware is no longer been registered in the Kernel.php file under the app/Http directory due to the changes. It is registered in the app.php file under the bootstrap directory.

💡
The middleware is registered within the →withMiddleware() chain method.

The middleware can be registered globally or assigned to specific routes.

Global Middleware

The global middleware is applicable to every request in the application. It is applicable to every HTTP request to the an application.

In previous versions of Laravel it is usually registered within app/Http/Kernel.php file

protected $middleware = [ \App\Http\Middleware\CheckRole::class ];

but in Laravel 11 it is done in the app.php file under the bootstrap directory.

    ->withMiddleware(function (Middleware $middleware) {
         $middleware->append(CheckRole::class);
    })

Assigning Middleware

In previous versions of Laravel to apply middleware to specific routes, it is registered in the $routeMiddleware array in app/Http/Kernel.php:

protected $routeMiddleware = [
    'CheckRole' => \App\Http\Middleware\CheckRole::class,
];

But in Laravel 11 it is registered in the bootstrap/app.php file as shown below:

Using aliases

  ->withMiddleware(function (Middleware $middleware) {
//define an alternative name for the middleware
        $middleware->alias([
            'checkRole' => CheckRole::class,
        ]);
    })

Using appendToGroup

Multiple Middleware grouped in the app.php

//in app.php
 $middleware->appendToGroup('auth-role', [
        CheckRole::class,
        Auth::class,
    ]);

//using the auth-role in web.php
Route::get('home', function () {
    return 'home';
})->middleware(['auth-role'])->name('home');
💡
You can create and register multiple middleware in a Laravel application…..

Usage within Route file

Invoking the Middleware class

The middleware class can be invoked directly on a route or group of route

Route::get('home', function () {
    return 'home';
})->middleware(CheckRole::class)->name('home');

Single route:

Route::get('home', function () {
    return 'home';
})->middleware('checkRole');

Grouped route

Route::middleware('checkRole')->group(function () {
    Route::get('home', function () {
        return 'here';
    });

    Route::get('blog', function () {
        return 'blog';
    });
});

Multiple Middleware on a route

Route::get('home', function () {
    return 'home';
})->middleware(['checkRole', 'auth'])->name('home');

The user gets redirected to an error page if they’re not authenticated while trying to access the home page.

Exclude Route from Middleware


Route::middleware('checkRole')->group(function () {
    Route::get('home', function () {
        return 'home';
    });

    Route::get('/blog', function () {
        // ...
    })->withoutMiddleware('checkRole');
});

Conclusion

This article basically demonstrate the creation of middleware, how to register and make use of it in a Laravel 11 application. In my upcoming Laravel series i’ll dive deep into explaining Laravel middleware.

If you find this article useful please kindly share it with your network and feel free to use the comment section for questions, answers, and contributions.

💡
Follow me on Hashnode: Alemsbaja --- X: Alemsbaja ---- Youtube: Tech with Alemsbaja to stay updated on more articles

Did you find this article valuable?

Support Alemoh Rapheal Baja by becoming a sponsor. Any amount is appreciated!