Laravel-如何将API资源递归转换为数组?

Ale*_*ldi 3 php laravel laravel-response laravel-5.6 laravel-resource

我正在使用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')
        )
    ];
}
Run Code Online (Sandbox Code Playgroud)

然后解决:

$resolved = (new PreorderResource(
  $preorder->load('driver')
))->resolve();
Run Code Online (Sandbox Code Playgroud)

乍一看,该方法可以解决问题,但问题是它无法递归工作。我的资源解析如下:

array:3 [
  "id" => 8
  "exception" => null
  "failed_at" => null
  "driver" => Modules\User\Transformers\DriverResource {#1359}
]
Run Code Online (Sandbox Code Playgroud)

如何解析API资源以递归数组?

the*_*ien 10

最简单的方法是生成 json 并转换回数组。

$resource = new ModelResource($model);
$array = json_decode($resource->toJson(), true);
Run Code Online (Sandbox Code Playgroud)


Mar*_*łek 5

通常,您应该这样做:

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

因为这是应该使用响应的方式(当然,您可以从控制器中进行响应)。

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

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

    echo $jsonResponse->getData();
});
Run Code Online (Sandbox Code Playgroud)

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

您还可以使用:

echo $jsonResponse->getContent();
Run Code Online (Sandbox Code Playgroud)

如果您只需要获取字符串

  • @AlexandreThebaldi 好吧,你可以将 `true` 作为 `getData` 的参数传递,你会得到数组 (3认同)