[英]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.