Search code examples
laraveljson-api

How to load relations with { json:api } Client?


I am using the {json:api} Client to parse json into Eloquent like models.

I have two models, Congress and Speaker. A Congress has many Speaker.

This is what I was able to do:

$repository = app(App\Repositories\CongressRepository::class);
$document = $repository->all();

$document is a CollectionDocument with the following attributes:

enter image description here

I would like to get the speakers of the first Congress. This is what I tried

$congresses = $document->getData();
$congress = $congresses->first();
$congress->speakers // <- this is null!

Why is $congress->speakers null? I also tried to us $repository->all(['includes' => 'speakers']); but this makes no differences.


Solution

  • It seems that $congress->speakers was null because the relation was null:

    enter image description here

    I use this package to create the json output. Inside the Schema.php I had to add self::DATA to make the data visible, as explained in the docs.

    public function getRelationships($resource, $isPrimary, array $includeRelationships)
    {
        return [
            'speakers' => [
                self::SHOW_SELF => true,
                self::SHOW_RELATED => true,
                self::DATA => function () use ($resource) {
                    return $resource->speakers;
                },
            ],
        ];
    }
    

    I still wonder if its possible to load the relation, if only the link is given in the API.