TechnicalMedium PHP & Laravel

What is middleware in Laravel? Give examples of when you would use it.

Asked for Backend Developer, Full-Stack Developer

Why they ask this: Middleware is how cross-cutting concerns like auth are handled; it shows you understand the request lifecycle.

Answer

Middleware is a layer that every matching HTTP request passes through before it reaches the controller, and the response passes back through after. Each middleware can let the request continue ($next($request)), change it, or stop it early.

Common uses:

  • Authentication: auth / auth:sanctum reject guests.
  • Authorisation and roles: for example only admins can reach /admin.
  • Rate limiting: throttle:60,1.
  • CORS, CSRF protection, logging, setting the locale.
php
class EnsureUserIsAdmin
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! $request->user()?->is_admin) {
            abort(403);
        }

        return $next($request);
    }
}

Route::middleware(['auth', EnsureUserIsAdmin::class])->group(function () {
    Route::get('/admin', AdminDashboardController::class);
});

Can you explain this in your own words?

Back to question bank