简体   繁体   中英

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. so the api returns back an array of users with a id and name field. When I convert the json to models I get the correct number of elements but all the attributes in the model are null.

I tried using bothe the hydrate and fill on the model to convert the json into models.

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

The json returns back ids and names that are not null

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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