What Middleware Does

A middleware is a class with a handle(Request $request, Closure $next) method. It may inspect or change the request, then call $next($request) to hand it to the next layer, and it receives the response that comes back. Code before that call runs on the way in; code after it runs on the way out. A middleware that returns a response without calling $next stops the request there: that is how auth redirects a guest, how throttle answers 429 and how an API-key check answers 401, all before a controller or a database query runs.

Laravel 2,157 builds the stack from three sources, in this order: the global middleware that wraps every request, the group assigned to the route file (web for routes/web.php, api for routes/api.php), and the route middleware named on the route or its group (Route Groups). The result is an onion.

The middleware onion: each layer runs its before code, calls $next, then its after code
The middleware onion: each layer runs its before code, calls $next, then its after code

Use middleware for HTTP concerns shared by many routes (headers, authentication, locale, rate limits); business rules belong in controllers, form requests and policies (Authorization).