Using getParsedBody in middleware


#1

In a route i’m able to use $request->getParsedBody() to obtain values from the body. I use the values to do some validations. I would like to move these validations to middleware. Now when i access $request->getParsedBody() within my middleware, it returns NULL.

What is going on here? Is it not possible to read the body in middleware?


#2

Check the config of your app and make sure determineRouteBeforeAppMiddleware is set and true:

'determineRouteBeforeAppMiddleware' => true

Then in your middleware (assuming JSON here):

$requestBody = $request->getBody();
$requestObject = json_decode($requestBody);

// code to validate or alter $requestObject 

$request = $request->withParsedBody($requestObject);
return $next($request, $response);

#3

Thanks for your reply. It works great for me!