Laravel Middleware Create and Use in Project

Middleware in laravel is a special class that is used for filtering http request before sending it to final output. Using laravel middleware we can filter http requests based on role, specific condition, headers or something else. In Laravel 11 creating middleware is so much easy with some steps. In this article we will make middleware and how it is used laravel application . 

Define middleware

php artisan make:middleware DemoMiddleware
DemoMiddleware
namespace App\Http\Middleware;

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

class DemoMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->isMethod('POST')) { //you can write any logic here
            abort(403);
        }
        return $next($request);
    }
}

This DemoMiddleware will be located inside app/Http/Middleware directory


Let's add this middleware in our bootstrap/app.php file

//bootstrap/app.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',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append: [
            \App\Http\Middleware\HandleInertiaRequests::class,
            \Illuminate\Http\Middleware\AddLinkHeadersForPreloadedAssets::class,
            \App\Http\Middleware\DemoMiddleware::class,
        ]);

        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Use middleweare in route level

If we want to use our defined middleware in route level then we can use this in in route group or use for single route


Middleware use in route groups
//routes/web.phpp

Route::middleware([
    'auth:sanctum',
    config('jetstream.auth_session'),
    'verified',
    \App\Http\Middleware\DemoMiddleware::class,
])->group(function () {
    Route::get('/dashboard', function () {
        return Inertia::render('Dashboard');
    })->name('dashboard');
});

Middleware use for single route
//routes/web.phpp

Route::middleware([
    'auth:sanctum',
    config('jetstream.auth_session'),
    'verified',
])->group(function () {
    Route::get('profile',[UserProfileController::class,'show'])
		->middleware([\App\Http\Middleware\DemoMiddleware::class]);
});

You can use middleware based on your needs 

Tags: