Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slim - modify POST request body inside middleware

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:

  • in the middleware: validate incoming json with defaults. this produces a modified object
  • write the modified object back into the request, so that it can be processed by the core controllers

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.

like image 753
tscherg Avatar asked Jul 11 '17 15:07

tscherg


Video Answer


1 Answers

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:

  • From there on, the request will hold a parsed object as body and on calling $request->getParsedBody() it won't be reparsed, if I understand the source correctly
  • on calling $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.

like image 184
tscherg Avatar answered Oct 10 '22 19:10

tscherg