从控制器到视图的JSON API响应

时间:2019-09-15 15:30:15

标签: php json laravel

我正在尝试从控制器传递JSON响应以进行查看,但JSON数组已更改。 当我从Api获得时如何传递JSON数组。

控制器代码:

$client = new Client();
        $response = $client->request('GET', env('API_URL').'/profile_question', [
            'headers' => [
                'Accept' => 'application/json',
                'Authorization' => 'Bearer '.$accessToken,
            ],
        ])->getBody();

        $response = json_decode($response);

        return view('account/incomplete_profile', compact(['response']));

dd在控制器中的结果:

{#273 ▼
  +"swingstatus": array:3 [▶]
  +"searchingfor": []
  +"language": []
  +"headline": []
  +"description": []
  +"lookingfor": []
  +"birthday": []
  +"eyes": []
  +"haircolor": []
  +"height": []
  +"weight": []
  +"bodytype": []
  +"raceethnics": []
  +"smokes": []
  +"piercings": []
  +"tattoos": []
  +"sexuality": []
  +"hasexperience": []
  +"looksareimportant": []
  +"integlligence": []
  +"hairlength": []
  +"bodyhair": []
  +"comfortlevel": []
  +"whatdoyoulike": []
  +"fetish": []
}

从视角来看:

array:3 [▼
  0 => {#284 ▶}
  1 => {#289 ▶}
  2 => {#287 ▶}
]

有人可以帮助我在我的视图内获取Api输出而无需更改吗?

1 个答案:

答案 0 :(得分:0)

似乎您正在混用命名

$response = json_decode($response);

尝试

$r = json_decode($response);

并且因为您要从api获取数据,而不是尝试将数据收集到laravel集合中

$collections = collect($r);

现在可以进入视野

return view('account.incomplete_profile', compact('collections'));

希望这会有所帮助