【问题标题】:Laravel - How to convert API Resource to array recursively?Laravel - 如何递归地将 API 资源转换为数组?
【发布时间】:2019-03-03 12:06:32
【问题描述】:

我正在使用 Laravel API Resource 并希望将实例的所有部分转换为数组。

在我的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 资源解析为递归数组?

【问题讨论】:

  • 我认为问题出在 DriveResource 上。你能在 DriverResource 中显示代码吗?

标签: php laravel laravel-5.6 laravel-response laravel-resource


【解决方案1】:

通常,您应该这样做:

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();

如果你只需要获取字符串

【讨论】:

  • 太棒了!使用getData() 得到的结果符合我的要求。现在我只需要将 stdClass 转换为数组
  • @AlexandreThebaldi 好吧,您可以将true 作为getData 的参数传递,然后您将获得数组
  • 完美答案!
【解决方案2】:

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

$resource = new ModelResource($model);
$array = json_decode($resource->toJson(), true);

【讨论】:

    【解决方案3】:

    迟到的答案,你也可以选择:

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

    如果您只想要数组字符串,请删除外部json_decode

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 2020-10-01
      • 1970-01-01
      • 2018-08-05
      • 2021-11-24
      • 2012-02-14
      • 1970-01-01
      相关资源
      最近更新 更多