DEV Community

Techsolutionstuff
Techsolutionstuff

Posted on • Originally published at techsolutionstuff.com

How to Create Custom Middleware in Laravel 11

In this article, we'll explore the process of creating custom middleware in Laravel 11.

Laravel 11 introduces significant changes to middleware handling. In previous versions, you could register middleware in the Kernel.php file.

However, with Laravel 11, you must define middleware in the app.php file.

Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application.

So, let's see laravel 11 creates custom middleware, how to customize default middleware in Laravel 11, and middleware in laravel 11.

Step 1: Install Laravel 11

First, we'll install laravel 11 using the following command.

composer create-project --prefer-dist laravel/laravel laravel-11-example
Enter fullscreen mode Exit fullscreen mode

Step 2: Create Middleware

Now, we'll create middleware using the following command.

php artisan make:middleware IsAdmin
Enter fullscreen mode Exit fullscreen mode

app/Http/Middleware/IsAdmin.php

<?php

namespace App\Http\Middleware;

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

class IsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (\Auth::user()->role_id != 1) {
            return response()->json('Opps! You do not have permission to access.');
        }

        return $next($request);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Register Middleware

In this step, we will register our custom middleware in the app.php file, as illustrated in the code snippet 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([
            'isAdmin' => \App\Http\Middleware\IsAdmin::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();
Enter fullscreen mode Exit fullscreen mode

Step 4: Apply Middleware

In this step, we'll create two routes and apply the "isAdmin" middleware. Let's proceed by updating the code accordingly.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

Route::middleware(['isAdmin'])->group(function () {
    Route::get('/dashboard', function () {
        return 'Dashboard';
    });

    Route::get('/users', function () {
        return 'Users';
    });
});
Enter fullscreen mode Exit fullscreen mode

Step 5: Run the Laravel 11 Application

Run the laravel 11 application using the following command.

php artisan serve
Enter fullscreen mode Exit fullscreen mode

You might also like:

Read Also: How to Create Custom Class in Laravel 11

Top comments (0)