I am using Slim v3 and the json schema validator by justinrainbow for my API. What I want to do and just can't get to work is:
What I am failing at is:
# inside middleware:
$requestbody = $request->getBody();
$requestobject = json_decode($requestbody);
# validation and modification of $requestobject takes place here
$request->getBody()->write(json_encode($requestobject));
$request->reparseBody();
return $next($request, $response);
From that point on, the request body is just null
. What am I doing wrong? I am rather certain that there is something wrong with the way I am modifying Slim objects, because it does not work when I manually try $request->getBody()->write('{"some": "content"}')
as well.
The solution was withParsedBody()
:
# inside middleware:
$requestbody = $request->getBody();
$requestobject = json_decode($requestbody);
# validation and modification of $requestobject takes place here
$request = $request->withParsedBody($requestobject);
return $next($request, $response);
It completely overwrites the request body with the modified object, just as I needed. What you have to pay mind to:
$request->getParsedBody()
it won't be reparsed, if I understand the source correctly$request->getParsedBody()
you usually get an associative array if the body was JSON, but using the snippet above, the parsed body will be an object instead.May the snippet be helpful to users in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With