[英]Converting Guzzle response t Laravel models
我正在尝试从json api获取数据并将返回的数组转换为模型的集合。 因此api返回具有id和name字段的用户数组。 当我将json转换为模型时,我得到了正确数量的元素,但是模型中的所有属性均为null。
我尝试同时使用水合物和填充模型以将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,
];
}
}
通话结束后,控制器返回
{“ data”:[{“ id”:null,“ name”:null},{“ id”:null,“ name”:null}]}
json返回不为null的id和名称
我正在测试此代码,并且工作正常:
$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,
];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.