Exiting Middleware processing and returning a response


#1

Lets say I have 3 middlewares which are processed for each request. Is it somehow possible to abort further processing of middles in (for example) Middleware #2 and send a response to the requesting browser? How would this be achieved?


#2

You can conditionally return a response before you call the next middleware. Or just don’t call next and return the response if you know no further processing is required.

    public function __invoke(Request $request, Response $response, $next)
    {
        if (!$user) {
            return $response; // short circuit the rest of the middleware
        }

        $response = $next($request, $response);

        return $response;
    }

#3

Great, thank you, will try this tonight …

Edit: works like a charm, thanks a lot!


#4

Great! Middleware can be strange to wrap your head around sometimes. I know it is for me.