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

Passing an array of object to laravel api resource showing Attempt to read property "code" on array

提问人:etranz 提问时间:11/17/2023 最后编辑:Brian Tompsett - 汤莱恩etranz 更新时间:11/17/2023 访问量:37

问:

我正在用 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
    ];
}
Laravel 资源 吞噬

评论

0赞 lagbox 11/17/2023
它说错误来自哪一行?
0赞 Hockic 11/17/2023
您确定复制了正确的错误吗?如果有的话,错误应该是,因为你的数据包含一个属性,但它缺少该属性undefined property $bankcodebank
0赞 etranz 11/17/2023
@Hockic 是的,我复制了正确的错误
0赞 Abdul Haseeb Khan 11/17/2023
在toArray函数中输入“dd($this);”,请分享结果,或者可能是您自己发现的错误

答:

0赞 etranz 11/17/2023 #1

我能够通过将 $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);
        }
    }