向laravel API资源传递对象数组,显示尝试读取数组上的属性“code”

lmyy7pcs  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(102)

我正在用laravel构建一个API。我想通过这个对象数组和API资源,这样我就可以只显示代码和名称,但我得到错误:
尝试读取数组上的属性"code"
这是数据:

[
    {
        "id": 132,
        "code": "560",
        "name": "Page"
    },
    {
        "id": 133,
        "code": "304",
        "name": "Mobile"
    }
  ]

字符串
这是我的控制器函数,它从API获取数据并将其推送到API资源:

public function getBanks(Utils $utils)
{

    $headers = [
        'Content-Type' => 'application/json',
        'Authorization' => 'Bearer xxxxxxx',
    ];

    $client = new \GuzzleHttp\Client();
    $response = $client->request('GET', 'my-api' , [
        'verify' => false,
        'headers' => $headers
        ]);
    $banks = json_decode($response->getBody(), true);
    return $utils->message("success", BankResource::collection($banks["data"])  , 200);

}


这是我的API资源函数:

public function toArray(Request $request): array
{
    return [
      "code" => $this->code,
      "bank" => $this->bank
    ];
}

lymnna71

lymnna711#

我能够通过将$banks[“data”]转换为std类来解决它

public function getBanks(Utils $utils)
    {
        $headers = [
            'Content-Type' => 'application/json',
            'Authorization' => 'Bearer ' . env("_KEY") ,
        ];
        try {
            $client = new \GuzzleHttp\Client();
            $response = $client->request('GET', 'https://api.xxxxxx.com/v3/banks' , [
                'verify' => false,
                'headers' => $headers
                ]);
            $banks = json_decode($response->getBody(), true);
            return $utils->message("success", BankResource::collection(json_decode(json_encode($banks["data"])))  , 200);

        }catch (\Throwable $e) {
            // Do something with your exception
            return $utils->message("error","Network Error. Please Try again" , 400);
        }
    }

字符串

相关问题