Can I pass values from routes to middleware?

I’ve got a variety of routes that do queries using Eloquent and then format them in a common way before outputting them as JSON. I’d like to move the formatting into some common middleware if possible - with the query object being passed from the route to the middleware and the middleware taking care of the output formatting.

Now, this would require passing values from a route to the middleware that’s going to run after it, but I don’t know how to do this. If it was the other way round then I could use $request->withAttribute(), but (as far as I can tell) there’s no way of passing the modified $request object back out to the middleware.

I might end up just using a function in each route to do the formatting, but I’d rather use middleware if I can.

This is how I have done something similar:

class SomeMiddleware
{
    public function __invoke($request, $response, $next)
    {
        $response = $next($request, $response);

        $newHTML = '<p>Hello</p>';

        $response->getBody()->write($newHTML);

        return $response;
    }
}

That could definitely work where the output of the route is HTML, or something that can be made into a stream, but what I’d prefer to output from the route is an object containing some data.

Maybe this isn’t really what middleware is intended for and I should just write a function that I use in all my routes to do the data formatting.

If this is based on data coming out of Eloquent models, you could write a Trait that performs the formatting, and use the Trait on any applicable models. When fetching the object you can then apply the formatting with the method from the Trait.

I’m doing something like that to obfuscate primary keys. I have a Trait that is used on various Eloquent models that formats the IDs.

But I could also be misunderstanding what it is you are trying to do. :slight_smile: