Laravel控制器POST请求后视图解析API JSON报错排查
问题场景与解决方法
我在Laravel控制器中编写了一段发送POST请求的代码,用来调用外部API获取数据:
public function CustomerCase($id) { $case = rental_request::with(['caseworker','user'])->where(['id'=>$id])->first(); $url = 'http://localhost:3000/api/priceByLocation'; $data = array('rentalObject' =>$case->attributesToArray()); $options = array( 'http' => array( 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data) ) ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); if ($result === FALSE) { /* Handle error */ } return view("case", ['case'=>$case, 'apiResult' => $result]); }
API返回的是JSON格式数据,我在Blade视图中尝试这样访问数据:
@if($apiResult) {{$apiResult->zipValues}} @else Not found @endif
结果直接报错:Trying to get property of non-object。
我一开始以为是没有把JSON字符串转成对象,于是把控制器的返回语句改成了:
return view("case", ['case'=>$case, 'apiResult' => json_decode($result)]);
但还是出现同样的错误,后来排查发现问题出在访问的层级不对——我试图直接从根对象获取zipValues,但实际上这个属性是嵌套在返回对象的某个子层级里的,调整访问路径后问题就解决了。
关键总结:
- 当API返回JSON数据时,必须先用
json_decode()把字符串转换成PHP对象/数组才能在视图中访问属性 - 报错
Trying to get property of non-object时,除了检查是否转码,还要确认属性的层级是否正确——可以先在控制器中用dd(json_decode($result))打印出完整的结构,确认要访问的属性具体在哪个层级下 - 另外建议给
json_decode()加上第二个参数true,转换成关联数组,有时候数组的访问方式($apiResult['xxx']['zipValues'])会更直观,也能避免对象属性访问的一些坑
内容的提问来源于stack exchange,提问作者Marc Rasmussen
相关产品推荐
相关产品推荐

