QA
Beginner LevelLaravel

How does HTTP Middleware intercept requests and responses in Laravel?

❓ Interview Prompt: Explain HTTP Middleware, the request/response pipeline, handle() method, and global vs route middleware.

Middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application.

Pipeline Flow:

Request $ ightarrow$ Middleware 1 $ ightarrow$ Middleware 2 $ ightarrow$ Controller Action $ ightarrow$ Response $ ightarrow$ Middleware 2 $ ightarrow$ Middleware 1 $ ightarrow$ Client.

Common Use Cases:

Authentication validation ('auth'), CSRF verification, rate limiting ('throttle'), and CORS header injection.

Code Implementation Example

php
<?php
namespace AppHttpMiddleware;

use Closure;
use IlluminateHttpRequest;
use SymfonyComponentHttpFoundationResponse;

class EnsureUserIsAdmin
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! $request->user()?->is_admin) {
            abort(403, 'Unauthorized access.');
        }
        return $next($request);
    }
}
💡Custom Laravel HTTP Middleware checking admin privileges.
🎯 Interview Key Takeaway

Middleware wraps route execution to perform request validation, authentication, and response transformation.

#Middleware#Request Pipeline#HTTP#Beginner
Back to all Laravel Questions→

More Laravel Interview Questions

Beginner LevelLaravel

How does the Laravel Service Container manage Dependency Injection and Bindings?

Beginner LevelLaravel

How does Routing work in Laravel including Named Routes and Route Parameters?

Beginner LevelLaravel

What is Blade Templating and how do custom directives work?