使用来自php post request(laravel)的数据

问题描述 投票:0回答:4

我的控制器中有以下帖子请求:

    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

enter image description here

现在在我看来,我希望访问这些数据,所以我做的是以下内容:

@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,我会收到以下错误:enter image description here

更新

我使用json_decode它是因为我试图获取根对象而不是对象的值!谢谢您的帮助!

php json laravel
4个回答
2
投票

看起来$apiResult是一个字符串,而不是一个对象。您从未在控制器中解码JSON,只是直接将其传递给变量。

只需将字符串直接注入Javascript,让你的JS代码在其中获得它想要的属性,即只写

{{$apiResult}}

(我假设您将其输出分配为JS变量。)

或者,在您的控制器中

'apiResult' => json_decode($result)

在return语句中将其转换为对象。


0
投票

你的$result是json。这意味着它是字符串而不是对象/数组。所以你需要转换它。使用json_decode()转换json字符串。所以在结果之后添加json decode语句

$result = file_get_contents($url, false, $context);
$result = json_decode($result);

0
投票

你不能在视图上显示对象或字符串,你必须在json_decode之后使用json_decode获得你的对象或数组。请注意,当您{{}}表示该值为字符串/数字/布尔值等时

在你的控制器中

return view('your-view')
->withApiResult(json_decode($result);

然后你会得到对象或数组

使用@foreach循环遍历数据并显示要显示的值

@foreach(cols as col)
   display data
@endforeach

0
投票

那是因为你正在尝试打印一个对象,请注意$apiResult->zipValues是一个对象,使用json_decode($result, true)将json转换为数组,然后使用blade foreach打印所有值

调节器

'apiResult' => json_decode($result, true)

视图

@foreach($apiResult['zipValues'] as $value)
    {{ $value }}
@endforeach
© www.soinside.com 2019 - 2024. All rights reserved.