Php 我想为Laravel中的空json抛出一个用户定义的异常

Php 我想为Laravel中的空json抛出一个用户定义的异常,php,json,laravel,if-statement,input,Php,Json,Laravel,If Statement,Input,我想检查输入json是否存在,并相应地返回一条消息。有两种方法可以验证这一点,使用isset($a)方法或使用$request->has('a')方法。但无论我使用哪种方法,如果我的输入json为null,它都会给出一个异常“Undefined property:stdClass::$a” 输入json:{}错误发生在代码的这一行 $a = $input->a; 这是在isset($a)支票之前。 试着像这样重写它: $input = json_decode(file_get_conte

我想检查输入json是否存在,并相应地返回一条消息。有两种方法可以验证这一点,使用isset($a)方法或使用$request->has('a')方法。但无论我使用哪种方法,如果我的输入json为null,它都会给出一个异常“Undefined property:stdClass::$a”


输入json:{}

错误发生在代码的这一行

$a = $input->a;
这是在isset($a)支票之前。 试着像这样重写它:

$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;
}

错误发生在代码的这一行

$a = $input->a;
这是在isset($a)支票之前。 试着像这样重写它:

$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;
}

谢谢,真的很有帮助。对于许多用户输入,有没有办法做到这一点?如果我有以下输入:a,b,c,d,e,f。因此,在本例中,是否有其他方法,或者我必须为每个输入运行if case?您可以尝试$request->filled()方法。所以不用“if(isset($input->a)){“try”if($request->filled(['a','b','c','d','e','f']){”。谢谢它真的很有帮助。有什么方法可以为许多用户输入这样做吗?例如:如果我有以下输入:a,b,c,d,e,f。那么在这种情况下有没有其他方法或者我必须为每个输入运行if case?你可以尝试$request->filled()所以,不要用“if(isset($input->a)){“try”if($request->filled(['a','b','c','d','e','f']){”。