Search code examples
laravelmiddleware

Difference between before and after middleware in Laravel 5.1


The only thing I know is that I have to do this:

$response = $next($request)
// some logic
return $response;

if I want middleware after the request is handled by the application and also when I use global middlewares, but I have absolutly no clue why I have to do this (I have noticed that I dont have access to $request->user() for example if I dont declare $response variable using global middeware, but I dont know why). Things i cannot understand are:

  • before/after the request is handled by the application - what does it exactly mean (other than one runs before and second after)?
  • How global middlewares defined in protected variable in kernel differs from after middlewares or what they have in common (cause rules during creating handle method are similar)?

I have tried to track down the laravel framework code itself but I think my skills are not enough.


Solution

  • Think about a middleware that checks access control before performing an action. If it's going to deny access, it has to run before the request is handled. The request handling is typically what is done in the relevant controller action.

    Another example is cookie encryption and decryption. The decryption is done in a before middleware so that when you are handling the request, you can read and write to the cookie normally. Then an after middleware encrypts the cookie before sending it to the client.

    Global middleware runs on every request, as opposed to middleware that is assigned to something (e.g. a route or a controller).