我正在使用 Laravel API 资源并希望将实例的所有部分转换为数组。
在我的PreorderResource.php
:
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'exception' => $this->exception,
'failed_at' => $this->failed_at,
'driver' => new DriverResource(
$this->whenLoaded('driver')
)
];
}
然后解决:
$resolved = (new PreorderResource(
$preorder->load('driver')
))->resolve();
乍一看,resolve方法适合它,但问题是它不能递归地工作。我的资源解析如下:
array:3 [
"id" => 8
"exception" => null
"failed_at" => null
"driver" => Modules\User\Transformers\DriverResource {#1359}
]
如何以递归方式将 API 资源解析为数组?