Wednesday, March 20, 2024

How to Create a Custom Middleware in Laravel 11


Laravel 11 brings notable changes to middleware handling, offering developers a refined approach to intercept and filter HTTP requests within their applications. In this tutorial, we'll delve into the process of creating custom middleware in Laravel 11, alongside customizing default middleware configurations.

Step 1: Installing Laravel 11

To kickstart our journey, let's install Laravel 11 by executing the following command:

composer create-project --prefer-dist laravel/laravel laravel-11-example

Step 2: Creating Middleware

Next, we'll craft custom middleware named "IsAdmin" using Laravel's artisan command:

php artisan make:middleware IsAdmin

This command generates a middleware class at app/Http/Middleware/IsAdmin.php, where we can define our middleware logic. Here's a snippet of the generated middleware class:

<?php


namespace App\Http\Middleware;


use Closure;

use Illuminate\Http\Request;

use Symfony\Component\HttpFoundation\Response;


class IsAdmin

{

    public function handle(Request $request, Closure $next): Response

    {

        if (\Auth::user()->role_id != 1) {

            return response()->json('Oops! You do not have permission to access.');

        }

        return $next($request);

    }

}

Step 3: Registering Middleware

In Laravel 11, middleware registration is performed in the app.php file. We'll alias our custom middleware within the middleware configuration block, as demonstrated below:

<?php


use Illuminate\Foundation\Application;

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([

            'isAdmin' => \App\Http\Middleware\IsAdmin::class,

        ]);

    })

    ->create();

Step 4: Applying Middleware

Finally, we'll apply our "isAdmin" middleware to specific routes in the routes/web.php file. This ensures that the middleware intercepts incoming requests to the specified routes:

<?php


use Illuminate\Support\Facades\Route;


Route::middleware(['isAdmin'])->group(function () {

    Route::get('/dashboard', function () {

        return 'Dashboard';

    });


    Route::get('/users', function () {

        return 'Users';

    });

});

Conclusion

In Laravel 11, crafting custom middleware offers enhanced control over request handling and authentication processes. By following the steps outlined in this tutorial, you can seamlessly integrate custom middleware into your Laravel applications, bolstering security and access control mechanisms.

0 comments:

Post a Comment