首页 > 解决方案 > 转换 Guzzle 响应 t Laravel 模型

问题描述

我正在尝试从 json api 获取数据并将返回的数组转换为模型集合。所以 api 返回一个带有 id 和 name 字段的用户数组。当我将 json 转换为模型时,我得到了正确数量的元素,但模型中的所有属性都是空的。

我尝试使用水合物和填充模型将 json 转换为模型。

        $client = new Client(); //GuzzleHttp\Client
        $request = new \GuzzleHttp\Psr7\Request('GET', 'https://test.com/users');
        $json = $client->sendAsync($request)->then(
            function ($response) {
                return $response->getBody()->getContents();
            }, function ($exception) {
                return $exception->getMessage();
            }
        )->wait();

$object = (array)json_decode($json);
$collection = User::hydrate($object);
return UserResource::collection($collection);

class UserResource extends JsonResource
{
    public static $wrap = null;

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {

        return [
            'id' => $this->name,
            'name' => $this->nameCombo,
        ];
    }
}

调用完成后,控制器返回

{"数据":[{"id":null,"name":null},{"id":null,"name":null}]}

json 返回不为空的 id 和名称

标签: phplaravelguzzle

解决方案


我正在测试这段代码并且工作得很好:

        $client = new Client(); //GuzzleHttp\Client
        $request = new \GuzzleHttp\Psr7\Request('GET', 'https://jsonplaceholder.typicode.com/users');
        $json = $client->sendAsync($request)->then(
            function ($response) {
                return $response->getBody()->getContents();
            }, function ($exception) {
            return $exception->getMessage();
        }
        )->wait();

        $object = (array)json_decode($json);
        $collection = User::hydrate($object);

        return UserResource::collection($collection);
class UserResource extends JsonResource
{
    public static $wrap = null;

    /**
     * Transform the resource into an array.
     *
     * @return array
     */
    public function toArray()
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
        ];
    }
}

你确定这部分是正确的吗?

        return [
            'id' => $this->name,
            'name' => $this->nameCombo,
        ];

推荐阅读