Resources

Relationships

To-one, to-many and polymorphic relationships, guessed from the model, loaded in batch.

A relationship is a descriptor too. It reads the relation named like the member (or the one given), loads it in batch for the whole document, and renders its linkage.

protected function toRelationships(Request $request): iterable
{
    return [
        'avatar' => $this->one(AvatarResource::class),
        // another relation name
        'my-avatar' => $this->one(AvatarResource::class, 'avatar'),
        // to-many, rendered only when loaded
        'comments' => $this->many(CommentResource::class)->whenLoaded(),
        // links and meta of the relationship
        'posts' => $this->many(PostResource::class)
            ->links(
                self: fn() => "https://api.example.com/users/"
                    . "{$this->resource->id}/relationships/posts",
                related: fn() => "https://api.example.com/users/"
                    . "{$this->resource->id}/posts",
            )
            ->meta(fn() => ['total' => $this->resource->posts()->count()]),
    ];
}
HelperRelationship
one(?string $resource, string|Closure|null $relation)to-one: HasOne, BelongsTo…
many(?string $resource, string|Closure|null $relation)to-many: HasMany, BelongsToMany…
morph(array $morphs, …)polymorphic to-one
morphMany(array $morphs, …)polymorphic to-many
PostResource::relationship(fn() => …)read by a closure; ->asCollection() for a to-many

Without resource class

On a resource of an Eloquent model, the resource class may be left out: it is guessed from the model, as Laravel's Model::toResource() does.

// optional when the convention applies:
// App\Http\Resources\PostResource → App\Models\Post
#[JsonApiModel(Post::class)]
final class PostResource extends JsonApiResource
{
    protected function toRelationships(Request $request): iterable
    {
        return [
            // the relation `user`
            'user' => $this->one(),
            // the relation `user`, under the name `author`
            'author' => $this->one('user'),
            // the relation `comments`
            'comments' => $this->many(),
        ];
    }
}

The related model is given by the relation (Post::user()->getRelated(): a public method of the model returning a relation; Eloquent's own methods, save()…, are never called), its resource by #[UseResource] on the related model, otherwise by the convention (App\Models\User → App\Http\Resources\UserResource). A first argument without namespace is a relation name.

It is guessed once, when the definition is compiled. A relationship that cannot be guessed (a resource of an array, a morphTo, a model without resource) is an error of the definition: pass the resource class there.

Loading

The relations a document renders are loaded before rendering, in batch on the whole collection: one query per relation and per include level, never one per resource.

  • A relationship read from a relation loads it. ->withLoad(false) disables it; ->withLoad('comments.user') or ->withLoad(['comments' => fn($query) => $query->latest()]) loads other paths, or constrains them. A constraint applies to the linkage and to the included resources alike.
  • A relationship read by a closure (PostResource::relationship(fn() => $this->resource->posts), or $this->one(…, fn() => …)) loads only what withLoad() declares.
  • A relation already loaded ($post->load('comments')) is not loaded again. Resources that are not Eloquent models are read as they are.
A relationship read by a closure without withLoad() runs one query per resource. Prefer $this->many(PostResource::class), or add ->withLoad('posts').

Linkage

A relationship that is not included still renders its resource linkage (data) by default. relationship.linkage changes that for the whole application (its links and meta are rendered in every case):

ValueNot included, not loadedNot included, loadedIncluded
always (default)data, loaded in batchdatadata and included
loadedno datadatadata and included
includedno data, the relation is not readno datadata and included

One relationship sets its own:

return [
    // `data` only when included
    'posts' => $this->many(PostResource::class)->whenIncluded(),
    // rendered only when loaded
    'comments' => $this->many(CommentResource::class)->whenLoaded(),
    // Ark4ne\JsonApi\Configuration\Linkage
    'author' => $this->one(UserResource::class)->linkage(Linkage::Always),
];

protected ?bool $autoWhenIncluded = true; on a resource applies whenIncluded() to all its relationships.

Identifier meta and pivots

meta() describes the relationship as a whole. Data belonging to the link to one related resource, such as a pivot, goes to the meta of its resource identifier:

toRelationships()
'tags' => $this->many(TagResource::class)
    ->identifierMeta(fn(TagResource $tag) => [
        'position' => $tag->resource->pivot->position,
    ]),
relationships.tags
{
  "data": [
    { "type": "tag", "id": "3", "meta": { "position": 1 } },
    { "type": "tag", "id": "7", "meta": { "position": 2 } }
  ]
}

For a BelongsToMany, ->pivotMeta(['position']) does the same from the pivot (->pivotMeta(['position'], 'membership') for a pivot renamed with as('membership')).

Filters and authorization

->filters() renders only the related resources passing every rule. Filters are immutable: return them.

'posts' => $this->many(PostResource::class)
    ->filters(fn(Filters $filters) => $filters
        ->can('view')
        ->when(fn($request, $post) => $post->is_public)),

->can('view') renders the whole relationship only when the user has the ability on the model.

Polymorphic relationships

A morphTo (or a closure giving models of several classes) renders each related model with the resource of the first class of the map it is an instance of: list a subclass before its parent.

return [
    'commentable' => $this->morph([
        Post::class => PostResource::class,
        Video::class => VideoResource::class,
    ]),
    'feed' => $this->morphMany([
        Post::class => PostResource::class,
        Video::class => VideoResource::class,
    ], 'items'),
];

A model of a class out of the map throws a RenderingException; the null items of a to-many are left out. include=commentable.author is valid when one of the related resources has author, path by path.

Server-side include

A resource or a collection includes paths whatever the request, in addition to its include:

return UserResource::make($user)->include('posts.comments');

These paths are neither validated by the Includes rule nor limited by include.max-depth.

Every modifier is listed in the relation helpers reference.