I want to check if the the input json is present or not and return a message accordingly. There are two methods to verify this, using isset($a) method or using $request->has(‘a’) method. But whichever method I use if my input json is null it gives an exception “Undefined property: stdClass::$a”.
JavaScript
x
$input = json_decode(file_get_contents('php://input', true));
$a = $input->a;
if(isset($a)){
$response = json_encode(array("response_code"=>200, "response_message"=>"Input present"));
return $response;
} else {
$response = json_encode(array("response_code"=>150, "response_message"=>"Input absent"));
return $response;
}
Input json: {}
Advertisement
Answer
The error happens on this line in your code
JavaScript
$a = $input->a;
Which is before the isset($a) check. Try rewriting it like this:
JavaScript
$input = json_decode(file_get_contents('php://input', true));
if(isset($input->a)){
$response = json_encode(array("response_code"=>200, "response_message"=>"Input present"));
return $response;
} else {
$response = json_encode(array("response_code"=>150, "response_message"=>"Input absent"));
return $response;
}