Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I register a middleware in Laravel 11?

Laravel 11 does not come with a middleware file and the kernel.php file has been removed altogther. So, when I create a custom middleware, how do I register it?

I do not know where to register middleware. Laravel 11 has been very confusing.

like image 228
Asim Reyazuddin Avatar asked Dec 20 '25 01:12

Asim Reyazuddin


2 Answers

In laravel 11 you can not register in the kernel.php the middlewares anymore. However there is plenty of other way how you can register the middlewares.

If you want it to be triggered in every call you can append it to the bootstrap/app.php .

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

Otherwise you can add middlewares to specific route or route groups:

Route::get('/yourroute', function () {
    
})->middleware(YourMiddleware::class);

If you add a middleware to a route group but you dont want certain routes to trigger the middleware, you can use the withoutMiddleware method

Route::middleware([YourMiddleware::class])->group(function () {
    Route::get('/', function () {
        // ...
    });
 
    Route::get('/yourroute', function () {
        // ...
    })->withoutMiddleware([YourMiddleware::class]);
});

For more information check out the official documentation: https://laravel.com/docs/11.x/middleware#registering-middleware

like image 159
Mátyás Grőger Avatar answered Dec 22 '25 20:12

Mátyás Grőger


In Laravel 11, You can add/register middlewar in bootstrap/app.php

->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'admin' => \App\Http\Middleware\AdminMiddleware::class,
    ]);
})

And In web/routes.php

Route::get('/link',[YourController::class,'method'])->name('route.name')->middleware('admin');
like image 28
Arif Avatar answered Dec 22 '25 21:12

Arif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!