Laravel - How to convert API Resource to array recursively?
Asked Answered
F

3

11

I'm using Laravel API Resource and want to convert all parts of my instance to an array.

In my 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')
        )
    ];
}

Then to resolve:

$resolved = (new PreorderResource(
  $preorder->load('driver')
))->resolve();

At first glance, the method resolve would fit it but the problem is that it doesn't work recursively. My resource resolved looks like:

array:3 [
  "id" => 8
  "exception" => null
  "failed_at" => null
  "driver" => Modules\User\Transformers\DriverResource {#1359}
]

How to resolve an API Resource to array recursively?

Fug answered 27/9, 2018 at 14:24 Comment(1)
I believe the issue is with the DriveResource. can you show the code in the DriverResource?Omura
V
13

Normally, you should just do:

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

because this is how responses should be used (of course you can do it from your controller).

However if there is any reason you want to do it manually you can do:

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

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

I'm not sure if this is exact effect you want, but you can get also other information from $jsonResponse if you need. And result of ->getData() is object.

You can also use:

echo $jsonResponse->getContent();

if you need to just get string

Vesicant answered 27/9, 2018 at 17:4 Comment(3)
Great! the result by using getData() fits what I'm looking for. Now I just have to convert the stdClass to arrayFug
@AlexandreThebaldi Well, you can just pass true as argument of getData and you will get array insteadRompers
Perfect answer!Fug
O
13

Easiest way is to generate json and convert back to array.

$resource = new ModelResource($model);
$array = json_decode($resource->toJson(), true);
Obnubilate answered 13/7, 2021 at 16:46 Comment(0)
A
0

The late answer, you could also go with:

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

In case you want only array string you remove the outer json_decode.

Adjectival answered 20/3, 2021 at 8:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.