Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

stratboy's avatar

When do middlewares run?

Hi, this is a low-level question... :P I was just studying the Laravel's request lifecycle. I read several articles, but still I'm not sure WHEN middlewares are run. I know middleware are found and used in various ways:

  • some are bootstrapped by the Kernel: are they always executed in 'background' despite if they are explicitly called or not? I mean http sessions, csfr tokens, maintenance etc..

  • they can be defined by the programmer or by other services/tools/plugins

  • they can be defined from controllers

  • they are explicitly executed from controllers or defining router like this:

Route::get('/something', function (...) {
    //
})->middleware('some');

And the above syntax seems to say: 'first return a response, than pass it to middleware', while in fact it's not the case, I guess. And by reading official docs:

If the request passes through all of the matched route's assigned middleware, the route or controller method will be executed and the response returned by the route or controller method will be sent back through the route's chain of middleware.

I guess one can pass the request to middlewares before returning a response, and then pass the response to other middlewares (but why?)? And thus: what's the syntax for the two operations? I know there are a lot of docs about middlewares but still I don't perfectly get the thing. Could you please shed some light?

Thank you

0 likes
3 replies
mabdullahsari's avatar
Level 16

There are 2 kinds of middleware

  • Global
  • Route specific

Global middleware can be found at the top of the HttpKernel class which run for every single incoming request for your app. This is where stuff like converting empty strings to null are done, or handling CORS requests.

Route specific middleware are gathered from various sources: route group definition, individual route or controller. It is also possible to inject this kind of middleware at runtime, which packages like Laravel Nova do to bootstrap the needed services when a request is determined to be a Nova request, but that's out the tangent.

A middleware can also be categorized as either a Before or After middleware. The former will perform some checks before passing on the request to the next middleware in the chain, whereas the latter will capture the application response and do some things with it. For example, you could define an After middleware to add some specific cache headers to the response.

The question is rather broad, but should provide a good understanding.

If you want to find out for yourself, start by looking at the Kernels handle method and go step by step until you reach the ControllerDispatcher.

1 like
furqanDev's avatar

In short Middlewares sit between your routes and controller.

Please or to participate in this conversation.