Skip to content

Instantly share code, notes, and snippets.

@ArielMejiaDev
Last active September 22, 2021 06:25
Show Gist options
  • Save ArielMejiaDev/0a97cce1303a57ac16f40e54adcb4d83 to your computer and use it in GitHub Desktop.
Save ArielMejiaDev/0a97cce1303a57ac16f40e54adcb4d83 to your computer and use it in GitHub Desktop.
Transform a resource to an associative array

resourceToArray snippet

Use to transform a resource to an associative array:

abstract class TestCase extends BaseTestCase
{

    //...

    /**
     * Convert the json resource instance to an array.
     * @param JsonResource $resource
     * @return array
     */
    public function resourceToArray(JsonResource $resource): array
    {
        return json_decode($resource->toJson(), 1);
    }

}

Usage

$post = Post::factory()->create();

$resource = $this->resourceToArray(PostResource::make($post));

$this->assertEquals($resource, [
    'id' => $post->id,
    'title' => $post->title,
    'content' => $post->content,
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment