Since Laravel 11 removes the Kernel class, how do we alias middleware? Let's take a look.
Pretty much everything you'd usually do within the Kernel
class has now been moved over to bootstrap/app.php
. It's not so obvious now, but it leaves your app feeling lighter with less boilerplate code.
Opening up bootstrap/app.php
, you'll notice a withMiddleware
method call. Here's what it looks like by default:
->withMiddleware(function (Middleware $middleware) {
//
})
Inside the withMiddleware
callback, call the alias
method on the Middleware
object that's passed in.
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'subscribed' => RedirectIfNotSubscribed::class
]);
})
Since this is an array, you can add as many aliases as required.
You can now use the alias anywhere in your routes or controllers.
Route::get('/protected', ProtectedController::class)
->middleware(['auth', 'subscribed'])
->name('protected');
Nice and easy. Although the change from Kernel may initially feel strange, I'm sure you appreciate how much cleaner it is to register aliases for your middleware now.