首页 > 解决方案 > Laravel - 如何递归地将 API 资源转换为数组?

问题描述

我正在使用 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 资源解析为数组?

标签: phplaravellaravel-5.6laravel-responselaravel-resource

解决方案


通常,您应该这样做:

Route::get('/some-url', function() {
    $preorder = Preorder::find(1); 
    return new PreorderResource($preorder->load('driver'))
});

因为这是应该使用响应的方式(当然你可以从你的控制器中做到这一点)。

但是,如果您出于任何原因想要手动执行此操作,您可以执行以下操作:

Route::get('/some-url', function() {
    $preorder = Preorder::find(1); 
    $jsonResponse = (new PreorderResource($preorder->load('driver')))->toResponse(app('request'));

    echo $jsonResponse->getData();
});

我不确定这是否是您想要的确切效果,但如果需要,您还可以从中获取其他信息$jsonResponse。结果->getData()是对象。

您还可以使用:

echo $jsonResponse->getContent();

如果您只需要获取字符串


推荐阅读