Create Middleware in Laravel 11 Application
Making or using middleware in laravel is a special need for sometimes. Middleware in laravel is a special class that is used for filtering http request before sending it to final output. In middleware we can filter request based on role, specific condition or something else. In Laravel 11 define middleware is so much easy with some steps. In this blog we will define middleware and try to see how it is used .Ā
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Ā