【问题标题】:Not able to check if property exists in API request object in laravel无法检查 laravel 的 API 请求对象中是否存在属性
【发布时间】:2020-10-25 14:01:21
【问题描述】:

我正在创建一个 API 控制器函数,该函数只有在我将在请求对象中获得 test_id 时才会执行,否则不会。我能够访问请求数据包并且我能够看到 test_id 属性它。我已经尝试了几种方法,但我无法检查它。这是我的控制器功能。我尝试使用 try catch 块,它显然输出 500 错误

ErrorException:未定义属性:文件 C:\xampp\htdocs\backendAPI\app\Http\Controllers\API\TestUploadController.php 中的 stdClass::$test_id

我已经解决了this 的问题并尝试了两种方法(isset() 和 property_exists()),但没有帮助我。即使我尝试了 echo/die() ,它们都没有返回任何内容。

public function addReadingTestData(Request $req){
        $module = 1;
        $request = $this->getRequestData($req);
        $isTestIdPResent = false;
         try{
             if($request->test_id){
                 $isTestIdPResent = true;
             }
         }
         catch(Exception $e){  
             $this->sendBAdRequestResponse('no test id');
         }
        if($isTestIdPResent){
            foreach($request->question as $ques){
                echo $ques->description."<br>";
                echo $ques->right_answer."<br><br>";
                echo implode($ques->possible_answers,',');
                echo "\n";
            }
        }else{
            return $this->sendBAdRequestResponse('Test Id does not exist.');
        }
    }

public function getRequestData($request){
        return json_decode($request::createFromGlobals()->getContent());
    }

public function sendBAdRequestResponse($errors){
        return response()->json(['error'=>$errors], 400);
    }

【问题讨论】:

    标签: php laravel api http laravel-api


    【解决方案1】:

    使用 laravel 验证检查$req

    你怎么能做到这一点?

    在这个答案中找到它

    https://stackoverflow.com/a/62589783/9579653

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 2018-01-01
      • 2020-11-30
      • 1970-01-01
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      相关资源
      最近更新 更多