Laravel interview question · Most asked
How does middleware work in Laravel, and where is it registered in recent versions?
Summary
Middleware wraps the request: each one receives the request and a $next closure, can act before and after calling $next, or return a response early. In Laravel 11 and later it is configured in bootstrap/app.php with ->withMiddleware(...) instead of an HTTP Kernel class.
Longer Answer
Middleware forms a pipeline. Code before $next($request) runs on the way in (authentication, rate limiting, setting the locale); code after it runs on the way out (adding headers, logging timings). Returning without calling $next short-circuits the request, for example a redirect to the login page.
Middleware can be global (every request), grouped (web, api) or assigned to routes by alias, and can take parameters (role:admin). Terminable middleware implements terminate() and runs after the response has been sent.
In Laravel 11's streamlined skeleton, app/Http/Kernel.php was removed; you append, prepend or alias middleware in bootstrap/app.php. Older applications upgraded in place can keep their Kernel.
Code Example
class EnsureUserIsAdmin
{
public function handle(Request $request, Closure $next): Response
{
if (! $request->user()?->is_admin) {
abort(403);
}
return $next($request);
}
}
// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
$middleware->alias(['admin' => EnsureUserIsAdmin::class]);
})
Key Points
- Pipeline of closures: before and after
$next. - Global, group and route middleware; parameters.
- Laravel 11+: configured in
bootstrap/app.php.
Explanation
Follow-up questions
- What does terminable middleware let you do?
- How would you add a request ID to every log line?
More most-asked Laravel questions
- How do you validate requests in Laravel? Why use Form Requests?
- Gates or policies: how does authorization work in Laravel?
- How do database transactions work in Laravel, and what pitfalls should you know?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- What is the service container, and how does dependency injection work in Laravel?
- What is the N+1 query problem in Eloquent and how do you prevent it?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- How do queues work in Laravel?