Created
May 21, 2015 12:49
-
-
Save andybeak/5a45a6f7aaaa48b75c59 to your computer and use it in GitHub Desktop.
Get post from body in Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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