Skip to content

Instantly share code, notes, and snippets.

@andybeak
Created May 21, 2015 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andybeak/5a45a6f7aaaa48b75c59 to your computer and use it in GitHub Desktop.
Save andybeak/5a45a6f7aaaa48b75c59 to your computer and use it in GitHub Desktop.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment