Labs ICT
โญ Pro Login

Middleware

Filtering HTTP requests.

Middleware

Middleware acts as a filter for HTTP requests entering your application. Think of it like security checkpoints โ€” each request must pass through them before reaching your routes.

Middleware can perform tasks like authentication, logging, CORS headers, rate limiting, and more. It's one of Laravel's most powerful features.

Built-in Middleware

Laravel comes with several ready-to-use middleware. You apply them directly to routes:

use Illuminate\Http\Request;

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware('auth');

Route::get('/api/data', function () {
    return response()->json(['key' => 'value']);
})->middleware('throttle:60,1');

Route::middleware('cors')->group(function () {
    Route::get('/api/users', [UserController::class, 'index']);
});

The auth middleware ensures the user is logged in. The throttle middleware limits requests โ€” here it's 60 per minute. The cors middleware handles cross-origin headers for APIs.

Creating Custom Middleware

You can create your own middleware with artisan:

php artisan make:middleware CheckAge

This generates a class in app/Http/Middleware/CheckAge.php. The handle method is where you put your logic:

class CheckAge
{
    public function handle(Request $request, Closure $next)
    {
        if ($request->age < 18) {
            return redirect('/home');
        }

        return $next($request);
    }
}

Register your middleware in the HTTP Kernel, then apply it to routes like any other middleware. The $next($request) call passes the request to the next layer.

Try it Yourself โ†’

Middleware Groups

When multiple routes need the same middleware, group them together in the HTTP Kernel:

protected $middlewareGroups = [
    'web' => [
        EncryptCookies::class,
        AddQueuedCookiesToResponse::class,
        StartSession::class,
        ShareErrorsFromSession::class,
        VerifyCsrfToken::class,
        SubstituteBindings::class,
    ],

    'api' => [
        'throttle:api',
        SubstituteBindings::class,
    ],
];

The web middleware group is applied automatically to all routes in routes/web.php. The api group is applied to routes/api.php. You can create custom groups for your specific needs.

๐Ÿงช Quick Quiz

What is middleware used for in Laravel?