How to Add Middleware in Laravel 12
In this tutorial, we will see how to add middleware in Laravel 12, Now we can use bootstrap/app.php instead of http/kernel.php this change came with the release of Laravel 11.
Create the middleware
First, let's assume that we want to add an admin middleware to protect the admin routes.
Let's create a new middleware. I gave it 'AdminMiddleware' as a name.
php artisan make:middleware AdminMiddleware
Register the middleware using an alias
Next, inside the file bootstrap/app.php let's register the middleware and give it 'admin' as an alias.
<?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->alias([
'admin' => \App\Http\Middleware\AdminMiddleware::class,
]);
})
->withExceptions(function (Exceptions $exceptions) {
//
})->create();
Check if user is an admin
Inside the 'AdminMiddleware', let's add the code to check if the logged-in user is an admin.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class AdminMiddleware
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (auth()->guard('admin')->check()) {
return $next($request);
}
return redirect()->back();
}
}
Use the middleware
Now, inside the web.php file, we can use the admin middleware to protect our routes.
Route::middleware('admin')->get('/admin', function () {
return view('dashboard');
});