Laravel 12 Middleware Registration Guide
Starting from Laravel 11, and continuing into Laravel 12, the traditional app/Http/Kernel.php file is no longer used for registering middleware. Instead, Laravel now handles middleware registration directly inside the bootstrap/app.php file. Here’s how you can register middleware in Laravel 12.
1. Define Your Middleware Class
Create your middleware using Artisan:
php artisan make:middleware ExampleMiddlewareThis will generate the file at:app/Http/Middleware/ExampleMiddleware.php
Example contents:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class ExampleMiddleware
{
public function handle(Request $request, Closure $next)
{
// Your custom logic here
return $next($request);
}
}
2. Register Middleware in bootstrap/app.php
Open bootstrap/app.php, and inside the ->withMiddleware(...) section, register your middleware.
To append your middleware to the web group, do this:
use App\Http\Middleware\EnsureTenantIsSet;
->withMiddleware(function (Middleware $middleware) {
$middleware->encryptCookies(except: ['appearance', 'sidebar_state']);
$middleware->web(append: [
ExampleMiddleware::class,
// Other middleware classes...
]);
})
3. Use on Specific Routes (Optional)
If you don’t want to apply it globally or to all web routes, you can assign it manually in route groups like this:
use App\Http\Middleware\ExampleMiddleware;
Route::middleware([ExampleMiddleware::class])->group(function () {
Route::get('/dashboard', fn () => Inertia::render('Dashboard'));
});Happy coding!!!
