简体   繁体   English

转换枪口响应t Laravel模型

[英]Converting Guzzle response t Laravel models

I am trying to get data from a json api and the convert the returned array into a collection of models. 我正在尝试从json api获取数据并将返回的数组转换为模型的集合。 so the api returns back an array of users with a id and name field. 因此api返回具有id和name字段的用户数组。 When I convert the json to models I get the correct number of elements but all the attributes in the model are null. 当我将json转换为模型时,我得到了正确数量的元素,但是模型中的所有属性均为null。

I tried using bothe the hydrate and fill on the model to convert the json into models. 我尝试同时使用水合物和填充模型以将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,
        ];
    }
}

When the call is finished the controller returns back 通话结束后,控制器返回

{"data":[{"id":null,"name":null},{"id":null,"name":null}]} {“ data”:[{“ id”:null,“ name”:null},{“ id”:null,“ name”:null}]}

The json returns back ids and names that are not null json返回不为null的id和名称

I am testing this code and works just fine: 我正在测试此代码,并且工作正常:

        $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,
        ];
    }
}

Are you sure this part is correct? 您确定这部分正确吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM