我的控制器中有以下帖子请求:
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]);
}
发布请求会返回以下JSON
:
现在在我看来,我希望访问这些数据,所以我做的是以下内容:
@if($apiResult)
{{$apiResult->zipValues}}
@else
Not found
@endif
但是在这里我收到以下错误:
Trying to get property of non-object
谁能告诉我我做错了什么?
使用json_decode
return view("case", ['case'=>$case, 'apiResult' => json_decode($result)]);
更新
我使用了json_decode
它是因为我试图获取根对象而不是对象的值!谢谢你的帮助!
答案 0 :(得分:2)
看起来$apiResult
是一个字符串,而不是一个对象。您从未在控制器中解码JSON,只是直接将其传递给变量。
只需将字符串直接注入Javascript,让你的JS代码获得它想要的属性,即只写
{{$apiResult}}
(我假设您将其输出分配为JS变量。)
或者,在您的控制器中执行
'apiResult' => json_decode($result)
答案 1 :(得分:0)
你的$result
是json。这意味着它是字符串而不是对象/数组。所以你需要转换它。使用json_decode()
转换json字符串。所以在结果之后添加json decode语句
$result = file_get_contents($url, false, $context);
$result = json_decode($result);
答案 2 :(得分:0)
你不能在json_decode视图上显示对象或字符串 在json_decode之后,您将获得您的对象或数组。 请注意,当您{{}}表示该值为字符串/数字/布尔值等
时 控制器中的
return view('your-view')
->withApiResult(json_decode($result);
然后你会得到objct或数组
使用@foreach遍历数据并显示您想要显示的值
@foreach(cols as col)
display data
@endforeach
答案 3 :(得分:0)
那是因为您正在尝试打印对象,请注意$apiResult->zipValues
是一个对象,使用json_decode($result, true)
将json转换为数组,然后使用blade foreach打印所有值
<强>控制器强>
'apiResult' => json_decode($result, true)
查看强>
@foreach($apiResult['zipValues'] as $value)
{{ $value }}
@endforeach