Skip to content
Advertisement

I want to throw a user defined exception for empty json in Laravel

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”.

$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

$a = $input->a;

Which is before the isset($a) check. Try rewriting it like this:

$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;
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement