Search code examples
laravellaravel-5.6laravel-middleware

Laravel difference between terminable middleware and after middleware


Larave middleware understanding source

It is mentioned that, there are two types of middleware: Before and after. Before middleware is handled before the request is handled and after middleware is handled after the request is handled.

But the function of terminable middleware is exact same as after middleware. Then what is the core difference between these two? Thanks.


Solution

  • Terminable Middleware runs after the response is ready and prepared.

    After Middleware runs after the request but before the response is prepared.

    So for example let's say you want to set a response header on all or a group of your responses, you can do so by using an after middleware. Because you need to set the header after you render the request but before you return the response. However if you want to store the session data in storage, you can use terminable middlware.

    This is the terminate method in TerminableInterface:

    /**
     * Terminates a request/response cycle.
     *
     * Should be called after sending the response and before shutting down the kernel.
     */
    public function terminate(Request $request, Response $response);
    

    You receive the request and response object in the terminate method of Terminable middleware, but changing the response would not take effect because the response has already been returned.