Get post from body in Laravel
/**
* getPostFromBody
*
* Returns an array obtained from reading and decoding the post body
* Optionally supply an array of fields that are required to be present
*
* @version 1.0.0
* @author Andy Beak
* @since 1.0.0
* @param array $requiredFields
* @access public
*/
public function getPostFromBody(array $requiredFields = []) {
$post = Request::getContent();
Log::debug(__METHOD__.' : Body content is ' . print_r($post,true));
if (empty($post)) {
throw new UserException('Please supply json encoded array of parameters in the request body');
}
$post = json_decode($post, true);
if (false === $post) {
throw new UserException('Could not decode the request - is it valid json?');
}
$post = $this->sanitizeArray($post);
if (!empty($requiredFields)) {
// check that all fields are present
$missingFields = [];
foreach ($requiredFields as $requiredField) {
if (!isset($post[$requiredField])) {
$missingFields[] = $requiredField;
}
}
if (!empty($missingFields)) {
throw new UserException('Missing compulsory fields : ' . implode(',', $missingFields));
}
}
return $post;
}