Type of included data is null with JsonApiSerializer in Fractal

299 views Asked by At

This is what I get at the moment with Fractal's JsonApiSerializer of Fractal in Laravel:

{
        "type": "projects",
        "id": "18",
        "attributes": {
            "name": "pariatur",
            "parent_id": 1
        },
        "relationships": {
            "tasks": {
                "data": [
                    {
                        "type": null,
                        "id": "245"
                    }
                ]
            }
        }
    }
],
"included": [
    {
        "type": null,
        "id": "435",
        "attributes": {
            "name": "incidunt",
            "content": "Laboriosam occaecati qui voluptas suscipit. Magni numquam incidunt pariatur et at. Alias molestias perspiciatis quae sit.",
            "project_id": 12,
            "due_at": "1971-05-19"
        }
    },

I know you can set the type for the requested resource like so:

// Important, notice the Resource Key in the third parameter:
$resource = new Item($book, new JsonApiBookTransformer(), 'books');
$resource = new Collection($books, new JsonApiBookTransformer(), 'books');

How can I do this for included data?

1

There are 1 answers

0
AudioBubble On BEST ANSWER

For people who may stumble upon this. I was missing that you need to set the ressourceKey in the corresponding transformer where you call collection() to include the data. Makes sense of course. In my case:

public function includeTasks(Project $project, ParamBag $paramBag)
{
    list($orderCol, $orderBy) = $paramBag->get('order') ?: ['created_at', 'desc'];

    $tasks = $project->tasks()->orderBy($orderCol, $orderBy)->get();

    return $this->collection($tasks, App::make(TaskTransformer::class), 'tasks');
}