Relationships and the relation DSL¶
Relations let a resource link to other resources. You declare them alongside
your attributes in fields(), and the library renders the JSON:API
relationships member — linkage (resource identifiers), conventional self and
related links, and (on request) the full related resources in included. This
page covers every relation type and the full policy surface that shapes how each
one renders, links, paginates, and mutates.
A relation is a field, so it shares the field builder surface
(storedAs(), computed(), extractUsing(), the read/write hooks) and adds a
relationship-specific surface on top. The related resource always serializes
through the serializer registered for its type, so you declare
the allowed related type(s) as the mandatory second argument to make()
(a single type for a monomorphic relation, a non-empty list for a polymorphic
one) and the registry does the rest. Declaring the related type also auto-adds a
RelationshipType inbound constraint, so a write that points the relation at the
wrong type is rejected.
Read the declared set back with the relatedTypes() accessor; for a polymorphic
relation the concrete member serializer is chosen per object at render time (the
resolveSerializer hook covered in serializers).
If you are new to the data model, concepts introduces relationships as a resource member; this page is the working reference.
The relation types¶
There are six relation field classes. The first four are monomorphic (one allowed related type); the last two are polymorphic (several).
| Class | Cardinality | Backing | Factory |
|---|---|---|---|
BelongsTo |
to-one | FK on the owning model | make('artist', 'artists') |
HasOne |
to-one | FK on the related model | make('featuredAlbum', 'albums'), or make('featuredAlbum', 'albums', 'artist') with a foreign key |
HasMany |
to-many | collection of related models | make('tracks', 'tracks'), or make('tracks', 'tracks', 'album') with a foreign key |
BelongsToMany |
to-many | pivot (join) table | make('playlists', 'playlists') |
MorphTo |
to-one | polymorphic FK | make('item', ['tracks', 'albums', 'artists']) |
MorphToMany |
to-many | polymorphic collection | make('items', ['tracks', 'albums', 'artists']) |
MorphMany and MorphOne aren't classes of their own: they build a HasMany and a
HasOne read through a MorphTo of the related type, see
a foreign key through a polymorphic relation.
The related resource type is a mandatory second argument to make() — a
single type for a monomorphic relation, a non-empty list for a polymorphic one.
A relationship cannot be declared without it.
By convention the relationship name is the domain property holding the related
object(s). BelongsTo::make('artist', 'artists') reads $album->artist;
HasMany::make('tracks', 'tracks') reads $album->tracks. No foreign-key
column, no extractor — the default reader
pulls the related value straight off the parent. You only reach for an override
when the related value is derived rather than stored (see
Custom relation hooks).
BelongsTo — a to-one foreign key¶
The common case. AlbumResource
declares its artist:
That single line renders album.relationships.artist with the artist's
identifier, the conventional self / related links, and — on ?include=artist
— the full artist in included. The related read endpoint GET /albums/1/artist
returns the artist resource; the linkage endpoint
GET /albums/1/relationships/artist returns just its identifier (see
related-endpoints).
When this relation appears in a write body, the default apply stores the parsed
linkage id on the field's column (Mode::Replace semantics). An empty to-one —
the related value is null — renders data: null rather than omitting the
member, which the linkage endpoint requires per the spec.
HasOne — a to-one foreign key on the related model¶
HasOne extends BelongsTo and carries identical metadata; the distinction is
advisory for data-layer adapters (the FK lives on the related model, not the
owning one). Name that foreign key as the third argument to read the target through it
instead of off the parent; see Reading through a foreign key. ArtistResource
declares one:
// src/Resource/ArtistResource.php
HasOne::make('featuredAlbum', 'albums'),
HasMany::make('albums', 'albums'),
GET /artists/1/featuredAlbum returns the featured album; an artist with none
renders data: null.
HasMany — a to-many collection¶
A to-many relation. AlbumResource's
tracks (the PagePaginator here is one of the paginators from
pagination; per-relation pagination
is covered below):
// src/Resource/AlbumResource.php
use haddowg\JsonApi\Pagination\PagePaginator;
HasMany::make('tracks', 'tracks')
->paginate(PagePaginator::make()->withDefaultPerPage(2)),
To-many relations add two cardinality bounds, minItems() / maxItems(), that
produce a 422 when a write supplies too few or too many members:
The OpenAPI document and the request validator's compiled schema carry the same bounds on the linkage of a create, an update and a relationship replacement. An addition or a removal sends only the members that change, so neither bounds it.
On a to-many mutation the default apply maintains a deduplicated id set under
the Mode of the request (the Mode enum, see
relationship-mutation): Mode::Replace sets the whole
set, Mode::Add appends (idempotently), Mode::Remove subtracts. See
relationship-mutation for the endpoints that drive
those modes.
Reading through a foreign key¶
HasMany and HasOne take an optional third argument, the foreign key: the field or
to-one relation of the related type that holds the parent's id. A relation declared
with one reads its members as the related rows whose foreign key is one of the parents'
ids, and never off the parent model:
// An inbox served by its own provider, whose items live in the database.
HasMany::make('items', 'inbox-items', 'user'),
// A field or a to-one relation of the related type, named either way.
HasMany::make('notes', 'notes', foreignKey: 'author'),
HasOne::make('latestReceipt', 'receipts', 'order'),
Use it when the parent can't hold its members. A singleton or a computed type served
by a custom provider has no association to read, and a database parent may have no
inverse mapping to the rows that point at it. Once declared, the foreign key decides
every read of the relation, whatever stores the parent and even when a mapped
association exists: the related endpoint, the relationship endpoint, ?include,
withData() linkage, ?withCount, offset and cursor pages, the
Relationship Queries profile and the related
type's filter defaults. The related type's data layer runs each as one query,
WHERE <foreign key> IN (<parent ids>) under its access scope, cut per parent to the
window it was asked for.
The foreign key must name a member of the related type that holds the parent's id:
- a stored field, compared with the parent's id as storage holds it, that is the parent's wire id decoded through its id encoder when it declares one;
- or a to-one relation whose related type is the parent's type, which may be a
MorphTodeclared withidentifiedByColumns().
RelationForeignKeyValidator checks that at warm-up, and a host runs it once per
registered resource. A BelongsToMany takes no foreign key, since its members live in
its pivot rows. The OpenAPI document doesn't change: the foreign key is how storage
reaches the members, not part of the API.
A data layer resolves the name with ForeignKey::of($relation, $resolver), which
returns the member's storage column and whether it is a to-one relation, and reads
each parent's key with ForeignKey::parentKey($parentSerializer, $parent).
A relationship write of such a relation is a write of the related rows, never of the
parent. A replace sets the foreign key on the rows the linkage names and clears it on the
members it leaves out, an add sets it, and a remove clears it on the named rows that are
members. A field takes the parent's id as storage holds it, and a to-one relation takes
the parent itself. The relation's mutation gates, readOnly() and
cannotChangeMembership() apply as on any relation, and a data layer refuses to clear a
foreign key its storage requires with the 403 of the mutation that drops the member.
Overriding HasMany::make() or HasOne::make() in a subclass now needs the third
?string $foreignKey = null parameter, since PHP checks a static method's signature
against its parent's.
A foreign key through a polymorphic relation¶
When the related rows point back at their parent through a MorphTo, declare the inverse
with MorphMany or MorphOne, naming that MorphTo:
// NoteResource
MorphTo::make('owner', ['posts', 'videos'])
->identifiedByColumns(type: 'ownerType', id: 'ownerId'),
// PostResource
MorphMany::make('notes', 'notes', 'owner'),
MorphOne::make('latestNote', 'notes', 'owner'),
MorphMany::make() builds the same HasMany as HasMany::make('notes', 'notes',
'owner'), and MorphOne::make() the same HasOne; the only difference is that warm-up
refuses them unless the member they name is a MorphTo of the related type.
HasMany::make() naming a MorphTo reads the same way.
A post's notes are then the notes whose ownerType holds a stored value naming posts
and whose ownerId holds one of the posts' keys, on every read the foreign key decides.
A write sets both fields on the rows that join, the type field to
MorphColumns::storedValueFor() the parent's type, and clears both on the rows that
leave. A data layer gets the two fields from ForeignKey::morphColumns(), which is null
for any other foreign key, and the stored values naming the parent's type from
MorphColumns::storedValues(). Core checks only that the member is a MorphTo; each data
layer checks that it can compare it, such as a MorphTo declared with
identifiedByColumns() on Doctrine or a native morphTo on Eloquent.
Naming the id field itself, HasMany::make('notes', 'notes', 'ownerId'), is refused at
warm-up, as is naming the type field: the id field holds the ids of posts and videos
alike, so the relation would read a video's notes as a post's whenever their ids match.
Name the MorphTo instead.
BelongsToMany — a pivot-backed to-many¶
A to-many backed by a join table, which can carry its own pivot columns.
TrackResource's
playlists:
// src/Resource/TrackResource.php
BelongsToMany::make('playlists', 'playlists')
->fields(
Integer::make('position')->min(1),
DateTime::make('addedAt')->readOnly(),
)
->cannotReplace(),
fields() declares the pivot (join-table) fields as real field definitions —
the same field DSL you use for attributes (Integer, Str, DateTime, …) with
their constraints, casts and read-only / context behaviour:
public function fields(FieldInterface ...$fields): static
public function pivotFields(): array // list<FieldInterface>
public function pivotField(string $name): ?FieldInterface
public function writablePivotFields(bool $creating): array // list<FieldInterface>
public function readablePivotFields(): array // list<FieldInterface>
public function readablePivotFieldsFor(JsonApiRequestInterface $request, mixed $relatedMember): array
One declaration drives every pivot concern:
- render — the field's value cast applies to the raw pivot column, and the
typed values render on each linkage member's
metaunder apivotkey (see below); - filter / sort — the field's name + column become a
filter[…]/sort=key on the related-collection endpoint; - write / validate — the field's constraints validate the incoming
meta, resolved by the operation's create vs update context exactly as for an attribute.
Rendering pivot fields — the meta.pivot linkage shape¶
On read, each linkage member carries its pivot values under a pivot key in
the member's meta — namespaced so they never collide with the related
resource's own intrinsic meta, and so a client can tell pivot data from member
meta. The values are the field-cast pivot column values, keyed by pivot field
name. GET /playlists/1/relationships/tracks (a BelongsToMany) renders linkage
members shaped like:
{
"data": [
{
"type": "tracks", "id": "7",
"meta": { "pivot": { "position": 3, "addedAt": "2026-01-01T00:00:00+00:00" } }
}
]
}
The same meta.pivot rides the full related resource on the related read
(GET /playlists/1/tracks) — the pivot values sit in the member resource's
top-level meta, alongside any intrinsic meta the type's serializer emits. Core
stays storage-agnostic: it carries the field definitions, and the host adapter
(the Symfony bundle's Doctrine adapter) reads the join row and supplies the typed
values it renders under pivot. The host renders every pivot field except a hidden or
write-only one, on every member, null when the join row holds no value. A member whose
pivot fields the request hides all of still carries "pivot": {}, so every member of the
linkage has meta.pivot. That is what the projected schema promises: each response
identifier requires meta and its pivot, and <Type><Rel>Pivot requires each field
whose visibility doesn't depend on the request.
readablePivotFields() is the request-independent list the OpenAPI schema documents.
It drops only the unconditionally hidden and write-only fields, so a field declared
with hidden(when:) or writeOnly(when:) stays in it. When rendering a member, a host
calls readablePivotFieldsFor($request, $member) once per member and renders exactly
the fields it returns. It applies writeOnly(when:) against the request and
hidden(when:) against the member.
A pivot field's hidden(when:) predicate receives the related member, the
far-side resource whose linkage (or related-read resource object) carries the
meta.pivot, as its model argument. It never receives the join row: that is a
Doctrine entity on one adapter, an Eloquent pivot model on another and a plain array
in a test double, so a predicate written against it would only work on one host.
// The playlist's `tracks` pivot hides `rating` on explicit tracks for a guest.
BelongsToMany::make('tracks', 'tracks')->fields(
Integer::make('position'),
Integer::make('rating')->hidden(
static fn(mixed $track, JsonApiRequestInterface $request): bool
=> $track->isExplicit() && $request->getHeaderLine('X-Role') !== 'admin',
),
),
Writing pivot fields — the linkage meta convention¶
A pivot field is writable by default; opt a server-owned column out with
->readOnly() (or ->readOnlyOnUpdate() / ->readOnlyOnCreate() for a
context-scoped opt-out). Pivot values are written through the JSON:API
resource-identifier meta on each linkage member, under the same pivot
key they render under (the spec allows a resource identifier to carry meta):
POST /playlists/1/relationships/orderedTracks
{ "data": [ { "type": "tracks", "id": "7", "meta": { "pivot": { "position": 3 } } } ] }
PATCH /playlists/1/relationships/orderedTracks
{ "data": [
{ "type": "tracks", "id": "7", "meta": { "pivot": { "position": 1 } } },
{ "type": "tracks", "id": "9", "meta": { "pivot": { "position": 2 } } }
] }
The same per-member meta rides the relationship when it appears inline in a
whole-resource POST / PATCH body. DELETE (remove) carries no pivot.
The relevant readers:
writablePivotFields($creating)returns the fields settable frommetain the given operation context (read-only ones filtered out by their context);- each parsed linkage member exposes its
metaon theResourceIdentifiervalue object ($identifier->meta) — on both the relationship-endpoint body and a relationship nested in a whole-resource body. No new wire-parsing surface was needed: a resource identifier has always parsed itsmeta.
Core stays storage-agnostic: it carries the field definitions and the parsed
meta, but never writes the join row. The Symfony bundle's Doctrine adapter is
the executor — it validates the meta against the writable pivot fields'
constraints (a violation is a 422 pointing at the linkage meta), and persists
the association entity as an upsert / reorder diff (update an existing row in
place, create a missing one, and on a full replace remove rows whose member is no
longer present). A read-only pivot field supplied in meta is never written. See
the bundle's relationships / Doctrine docs for the persistence details.
meta.pivot is a closed object. A member no pivot field names is a 422 pointing at it,
/data/0/meta/pivot/colour, where it used to be ignored. One AdditionalProperties entry
among the fields opens it:
BelongsToMany::make('tracks', 'tracks')->fields(
Integer::make('position'),
AdditionalProperties::make()
->of(Str::make('*'))
->extractUsing(fn (PivotEdge $edge): array => $edge->pivot['labels'] ?? []),
);
Its extractUsing() hook receives the PivotEdge and returns extra members to render beside
the declared ones. A write's undeclared members are validated against of() when it is given,
and handed together to the entry's fillUsing() hook. See
links and meta.
Computed pivot fields¶
A pivot field can be computed rather than stored: declare it with computed() or
computedUsing(), as you would a derived attribute. It has no column. Its hook does not
receive a join row. It receives a
PivotEdge holding the parent whose relation is
rendered, the related member the linkage identifier points at, and pivot, the link's
stored pivot values keyed by field name (empty when the link has no join row), so the
value is worked out per link:
BelongsToMany::make('members', 'users')
->fields(
Str::make('role')->computedUsing(
static fn(PivotEdge $edge): string => $edge->parent->roleOf($edge->related),
),
),
A computed field renders under meta.pivot like any other, through the field's own cast,
and hidden(when:) still receives the related member. It is never written:
writablePivotFields() leaves it out even when it is not declared readOnly(), a write
that sends it ignores it as it ignores a read-only field, and the projected
<Type><Rel>WritePivot does not list it. It has no column, so it is not a sort= or
filter[…] key either.
A stored field with an extractUsing() hook is not computed. As on an attribute, the hook
changes only how it is read: the field keeps its column, stays writable from meta, and
sorts and filters on its column. Its hook receives the same PivotEdge, never the join
row, and reads the stored value from $edge->pivot. A serializeUsing() hook on a pivot
field is not consulted.
isComputedPivotField() tells a computed field from a stored one, storedPivotFields()
and computedPivotFields() split the declaration, and readsPivotFieldThroughHook() names
the fields whose value comes from a hook. hookedPivotValues($parent, $related, $stored,
$request) evaluates those for a link, given the stored values the host read, and the host
renders them over the stored values. When storedPivotFields() is empty the relation
needs no association entity or pivot model at all, and a host serves it over a plain join
table.
The Doctrine fact. A plain
#[ORM\ManyToMany]join table holds only the two foreign keys — Doctrine cannot map aposition/addedAtcolumn on it. To have pivot columns the join must be modelled as an association entity (PlaylistTrack { int position; \DateTime addedAt; ManyToOne playlist; ManyToOne track }), with the parent owning aOneToManyto it and the association entity aManyToOneto the far type. The bundle's Doctrine adapter auto-detects this association entity from the parent's metadata.
When auto-detection is ambiguous (the parent has more than one to-many association
that could back the pivot) or finds nothing, name the association entity explicitly
with through() — an opaque, declare-only class-string that core carries but
never interprets (it stays storage-agnostic), and the host adapter reads as the
association entity backing the pivot:
public function through(?string $associationEntity, ?string $parent = null, ?string $related = null): static
public function pivotThrough(): ?string
public function pivotParentSide(): ?string
public function pivotRelatedSide(): ?string
BelongsToMany::make('tracks', 'tracks')
->fields(
Integer::make('position')->min(1),
DateTime::make('addedAt')->readOnly(),
)
->through(PlaylistTrack::class),
pivotThrough() reads it back (null when no override was declared). Passing
null clears an earlier override, and any side names with it.
The class can have more than one property pointing at the same type. A seat linking an
owner to another owner has two, and an adapter can't tell from the class alone which one
points back at the parent. parent: and related: name them, as strings core carries
without reading, like the class:
BelongsToMany::make('peers', 'owners')
->fields(Integer::make('rank'))
->through(Seat::class, parent: 'owner', related: 'peer'),
BelongsToMany::make('followers', 'owners')
->fields(Integer::make('rank'))
->through(Seat::class, parent: 'peer', related: 'owner'),
Either can be left out for the adapter to find. pivotParentSide() and
pivotRelatedSide() read them back. Naming a side without a class, naming it with an
empty string, or naming one member as both sides throws an \InvalidArgumentException. A
MorphToMany names its link rows' owner, type and id with identifiedByRows(), so it
refuses side names when it is built. What a name refers to, and whether a wrong one is
caught, is the adapter's: the Symfony bundle reads Doctrine associations, and the Laravel
adapter checks them against the Eloquent relation's pivot keys.
BelongsToMany extends HasMany, so it inherits minItems() / maxItems() and
the deduplicated-set apply. The cannotReplace() above is a mutation gate covered
in Mutation gates.
MorphTo — a polymorphic to-one¶
A to-one whose related resource may be one of several types. Declare the allowed
types as the non-empty-list second argument to make(); the related object's
serializer is resolved at runtime from its own getType().
FavoriteResource:
// src/Resource/FavoriteResource.php
MorphTo::make('favoritable', ['tracks', 'albums', 'artists'])
->extractUsing(static fn(mixed $favorite): ?object => $favorite instanceof Favorite ? $favorite->favoritable : null),
The same endpoint shape renders a different resource depending on the favorite:
GET /favorites/1/favoritable resolves a track, /favorites/2/favoritable an
album, /favorites/3/favoritable an artist — each through the serializer the
related object's type reports. A null related value renders data: null (the
linkage is bound to the first declared, registered serializer so the relationship
still carries a resource).
A MorphTo is polymorphic however many types it lists. The OpenAPI document describes
one over a single type as a union with one member, not as a BelongsTo, so adding a
type later doesn't change a generated client's shape; see
polymorphic relations with one type.
The same holds for MorphToMany.
The
extractUsing()here is the one custom reader in the example app — a polymorphic to-one is a natural place to need one when the related value is derived rather than a plain property. For a relation whose property matches its name, drop it. See Custom relation hooks.
Identifying the target without loading it¶
A MorphTo normally reads the related object to find out its type, so rendering the
linkage loads the target. When the parent stores the target as a type and id pair,
declare identifiedBy() and the linkage renders straight from the pair:
MorphTo::make('target', ['advertisers', 'agencies'])
->identifiedBy(static fn(mixed $campaign): ?array => $campaign instanceof Campaign && $campaign->targetId !== null
? [$campaign->targetType, $campaign->targetId]
: null),
The closure receives the parent and the request. It returns [$type, $id], with
$type one of the declared JSON:API types and $id the storage key, or null for an
empty relation. The id in the linkage goes through the target type's id encoder,
the same as it would if the target were rendered. A type the relation doesn't declare
throws a \LogicException, which renders as a 500; its message names the class that
declared the closure, the relation and the type.
The target is read only when the relationship is included. The host's
ToOneRelationshipLinkageInterface is asked first, and without one the relation's
usual read runs: the property named like the relation, or extractUsing(). Either
way the pair's type picks the serializer that renders the target, so one class can
back several declared types. When that serializer's getType() reports another type
for the target, the target is left out of included. A host-supplied
ToOneRelationshipLinkage::none() empties the relation, and a target supplied for an
empty pair renders nothing. Writes are unaffected, so fillUsing() still owns them,
and so is the OpenAPI document.
An identified relation is never lazy: the pair costs no
load, so it emits data whatever the load-state predicate says.
An identifierMeta() resolver on it
receives an IdentifiedMember as $related instead of the target: the type and id the
pair stores, before any id encoder, and no row. Its target is the object the host
supplied through its ToOneRelationshipLinkageInterface when there is one, as on an
identified MorphToMany, and null otherwise. Core never loads the target to fill it in:
when the request includes the relation, the target core reads renders into included
but the resolver doesn't see it, so the identifier's meta is the same with or without
?include. Whether a host supplies targets depends on the adapter, so a resolver that
reads target can see a different value from one adapter to another. Keying the meta on
the pair's type and id gives the same result everywhere:
use haddowg\JsonApi\Schema\Relationship\IdentifiedMember;
MorphTo::make('target', ['advertisers', 'agencies'])
->identifiedBy(static fn(mixed $campaign): ?array => $campaign instanceof Campaign && $campaign->targetId !== null
? [$campaign->targetType, $campaign->targetId]
: null)
->identifierMeta(
static fn(Campaign $campaign, IdentifiedMember $target, $request): array => [
'primary' => $campaign->isPrimary($target->type, $target->id),
],
fields: [Boolean::make('primary')->guaranteed()],
),
Declaring the pair's fields with identifiedByColumns()¶
When the parent keeps the pair in two fields of its own, name them instead of writing a closure:
MorphTo::make('subject', ['rfps', 'campaigns'])
->identifiedByColumns(type: 'subjectType', id: 'subjectId'),
Each name is a field of the parent as its model sees it, a Doctrine entity's property or
an Eloquent model's attribute. The linkage renders from the two fields exactly as it does
from a closure, and a parent whose type or id field is empty has no target. The stored type
is the target's JSON:API type unless typeMap maps stored values to types, as an Eloquent
morph map does:
->identifiedByColumns(type: 'subject_type', id: 'subject_id', typeMap: [
'rfp' => 'rfps',
'campaign' => 'campaigns',
]),
An id held as a \Stringable value object, such as a Symfony Uuid hydrated from a
uuid column, is its string form. A stored type the map doesn't name, or that names no
declared type, throws a \LogicException. Because the fields are declared, a data layer can compare them in a
query, which a WhereMorph
filter needs: MorphTo::identifierColumns() returns them as a MorphColumns, or null
for a relation identified by a closure. Like identifiedBy() it changes reads only.
The id field may hold the target's storage key, which is what a write through core stores,
or its wire id. The two differ only when the target type declares an
id encoder, and a text
column holding the ids of several kinds of target often keeps the wire form. The linkage, a
related read, an include and a WhereMorph accept either: StoredIdForms::wireId() turns a
stored id in either form into its wire id, and MorphTarget::storedForms() lists the forms
a filter compares a column against. Link rows declared with identifiedByRows() work the
same way, and a link row's id held as a value object is its string form too. A uuid-shaped id with no id encoder renders in lower case, as a uuid does, whatever case the column keeps. A data layer matches a column that keeps it all in lower case or all in upper case, binding both forms so an index on the column still serves the query, but not one that mixes case within an id. A stored id counts as a wire id when the encoder decodes it and encodes the result
back to the same id, so with an encoder whose storage keys also survive that round trip,
store one form consistently.
The build refuses these declarations:
| Declared | Why |
|---|---|
both identifiedBy() and identifiedByColumns() |
declare one |
| a field that is empty or a dotted path | name a field of the parent itself |
| the same field for the type and the id | they are two fields |
a typeMap value that isn't a declared type |
every stored value maps to one of the relation's types |
Keep identifiedBy() for storage two fields can't describe. A data layer can't compare a
closure in a query, so a WhereMorph needs identifiedByColumns() on the Doctrine and
in-memory providers.
The same two fields serve a HasMany or HasOne on each target type that reads the
target's rows back, named by the MorphTo: see
a foreign key through a polymorphic relation.
A data layer loads included and related targets from the pairs, one query per type.
MorphTo::storedIdentifiers($parents, $request) returns the stored ids of a page of
parents grouped by type, deduplicated, in declared order, and
storedIdentifier($parent, $request) returns one parent's pair. storesIdentifiers()
says whether a relation was declared this way.
MorphToMany — a polymorphic to-many¶
A to-many collection whose members may each be a different type.
LibraryResource:
The mixed members render through a single
PolymorphicSerializer decorator that resolves each member's
serializer against the declared types and delegates — so a collection of a track,
an album, and an artist each carries its own type. A member matching no
declared type throws a \LogicException.
A polymorphic to-many carries no shared filter/sort vocabulary across its mixed
member types, so filter and sort on its related collection return 400,
though page still slices it. An identified one with
pivot fields filters and sorts its link rows instead. The reference Doctrine adapter does not support a
polymorphic to-many related endpoint (its members span entity classes) — supply a
custom provider there; see related-endpoints.
Identifying the members without loading them¶
When the parent stores its members as link rows, each naming a company type and a
company id, declare the rows with through() and identifiedByRows() and the linkage
renders straight from them:
MorphToMany::make('companies', ['agencies', 'advertisers', 'publishers'])
->storedAs('userCompanies')
->through(UserCompany::class)
->identifiedByRows(owner: 'user', type: 'companyType', id: 'companyId'),
through() names the class backing the rows. owner is the row field pointing at the
parent, type the field holding the member's stored type and id the field holding its
storage key. Each is a field of the row as its model sees it, a Doctrine property or an
Eloquent attribute or relation, never a database column, so a data layer can query the
rows itself. Core reads them in memory as the relation's value on the parent, which
storedAs() or extractUsing() points at the parent's collection of rows.
The owner field must identify exactly one owning type. A data layer reads a parent's
rows by that field alone, with no owner type beside it, so a link table shared by several
owner types, whose owner ids may collide, isn't supported yet.
The stored type is the JSON:API type unless you pass typeMap, from stored value to
JSON:API type, as an Eloquent morph map stores agency for agencies:
->identifiedByRows(owner: 'user', type: 'company_type', id: 'company_id', typeMap: [
'agency' => 'agencies',
'advertiser' => 'advertisers',
'publisher' => 'publishers',
]),
Core never infers the map. A declared map holds exactly one stored value for each declared
type, so a new row has one value to write, and it is complete: a row whose stored type it doesn't
list is not a member. Without a map, a row whose type isn't a declared type is not a
member, and neither is a row with no id. A repeated pair renders once, and each id goes
through its type's id encoder.
The build fails with a \LogicException when:
| Declaration | Problem |
|---|---|
identifiedByRows() |
a field is empty or a dotted path, or one field fills two roles |
identifiedByRows() without through() |
a data layer has no row class to query |
a typeMap value |
names a type the relation doesn't declare |
a typeMap |
maps no stored value, or more than one, to a declared type |
both identifiedBy() and identifiedByRows() |
declare one |
fillUsing() with identifiedByRows() |
the data layer writes the rows, see writing link rows |
For storage these fields can't describe, declare identifiedBy() with a closure instead:
MorphToMany::make('companies', ['agencies', 'advertisers', 'publishers'])
->identifiedBy(static fn(mixed $user): array => $user instanceof User
? array_map(static fn(UserCompany $row): array => [$row->companyType, $row->companyId], $user->companies)
: []),
The closure receives the parent and the request and returns a list of [$type, $id]
pairs, with $type one of the declared JSON:API types and $id the storage key. The
linkage keeps the list's order, a repeated pair renders once, and each id goes
through its type's id encoder. A type the relation doesn't declare throws a
\LogicException, which renders as a 500; its message names the class that declared
the closure, the relation and the type. Only core can run the closure, so a closure
relation is served in memory: every request reads all of a parent's pairs, and its
endpoints filter, sort and page them in memory.
A member is read only when the relationship is included, and always renders with the
serializer of its pair's type, so one class can back several declared types. A member
whose serializer's getType() reports another type is left out of included, as for
MorphTo.
A host decides which members render by returning a RelationshipLinkage from its
RelationshipLinkageInterface, whose data lists IdentifiedMember values. Each
names a pair, IdentifiedMember::of($pair, $target), and may carry the target it
loaded for included. The supplied members replace the stored pairs, so a member the
host leaves out, hidden by a scope or gone from its table, is missing from the linkage
too. A supplied member without a target is matched against the relation's usual value
on the parent when it is included, unless the relation is declared with
identifiedByRows(), whose value on the parent is its rows. Without a seam the stored
pairs render as they are.
The pairs must point at rows that exist. A host loads or checks only the types whose rows a scope can hide, so a pair of such a type that no longer matches a row drops out and pages and totals stay exact. A dangling pair of a type nothing hides costs no query, so it still shows in the linkage, and a related page that reaches it can come back one member short.
As with MorphTo, an identified MorphToMany is never lazy. Declared with
identifiedBy() it changes reads only, so fillUsing() still owns writes. Declared with
identifiedByRows(), the data layer writes the link rows itself from a plan core computes,
as writing link rows describes, and the default
write leaves the parent's rows alone. Its relationship endpoint pages the pairs the way its
related endpoint does, so the OpenAPI document gives GET …/relationships/{name} the
same page and withCount parameters. Metadata reports the relation through
DeclaresIdentifiedMembers. An identifierMeta() resolver receives each member as its
IdentifiedMember, since the linkage renders without loading it: the pair, the link row
and the target when the host supplied one.
A data layer loads the members of a page of parents one query per type.
MorphToMany::storedIdentifiers($parents, $request) returns their ids grouped by type,
deduplicated, in declared order, and storedIdentifierList($parent, $request) returns
one parent's pairs in order. Both relations implement StoresIdentifiersInterface,
whose storesIdentifiers() says whether a relation was declared this way, and
MorphToMany::linkRowFields() returns the LinkRowFields an identifiedByRows()
relation declares.
Pivot fields on the link rows¶
An identified MorphToMany can declare pivot fields on the rows it reads its pairs from,
with the same fields() and through() a BelongsToMany
has: stored and computed fields and every field modifier.
MorphToMany::make('companies', ['agencies', 'advertisers', 'publishers'])
->storedAs('userCompanies')
->through(UserCompany::class)
->identifiedByRows(owner: 'user', type: 'companyType', id: 'companyId')
->fields(
Integer::make('position'),
DateTime::make('linkedAt')->readOnly(),
)
->withFilters(Where::make('minPosition', 'pivot.position', '>=')->integer()),
A data layer queries these rows directly, so on a relation declared with
identifiedByRows() every stored pivot field and every pivot. filter must name a field
of the row itself, not a dotted path, and a position can't be the owner, type or id
field. The build fails otherwise.
With identifiedBy(), return each member as a [$type, $id, $row] triple, $row the
link row its stored fields are read from:
->identifiedBy(static fn(User $user): array => array_map(
static fn(UserCompany $row): array => [$row->companyType, $row->companyId, $row],
$user->companies->toArray(),
))
The wire shape is a BelongsToMany's. Each identifier renders its readable fields as
meta.pivot, each stored field read off the row with its column and cast by the field,
null when the row holds nothing, and a write carries the writable ones in the same
meta.pivot. When the request hides every pivot field, pivot renders as {}.
identifierMeta() members sit beside pivot in the identifier's meta.
Declaring pivot fields without identifiedByRows() or identifiedBy() fails the build,
because only the link rows map a member to its type and id, and a member of a relation with stored pivot fields
that arrives without its row throws a \LogicException.
Its relationship and related endpoints accept sort and filter over the pivot fields
only, since the members span types and share nothing else:
| Parameter | Accepts |
|---|---|
sort |
the key of any stored pivot field, the same automatic sorts a BelongsToMany has |
filter[<key>] |
a withFilters() filter whose column starts with pivot., comparing that column of the row |
Both run over the link rows. Ties break by the stored type and then the id on a relation
declared with identifiedByRows(), and keep the closure's order on one declared with
identifiedBy(). A MorphToMany declared with neither still answers 400 to either. A default read order
may name a stored pivot field, and orders the linkage when the request names no sort.
A data layer reads the rows through a LinkRowQueryInterface.
LinkRowQuery::resolve($relation, $sort, $filter, $request, $window, $countable) turns a
request's values for the relation into sort and filter directives, falling back to the
relation's default sort, and rejects a key outside the pivot vocabulary with the usual
400. LinkRowQuery::sorts() and LinkRowQuery::filters() return that vocabulary, and
LinkRowQuery::rowColumn() strips the pivot. prefix to name the row's column. The
query returns IdentifiedMember values carrying their rows, which the host supplies as the
relation's linkage, and core renders each meta.pivot from its row.
MorphToMany::pivotValues($member, $parent, $request) returns the same values for a
member's resource object on the related endpoint. Both relations implement
PivotRelationInterface, so a host reads, validates and writes either relation's pivot
through one interface.
Querying link rows in a data layer¶
Core sets the rules for which rows count and in what order, so every data layer returns
the same page. LinkRowQuery::resolve() carries the relation's LinkRowFields as
$query->fields, null for a closure relation. A data layer serving a relation declared
with identifiedByRows() reads everything it needs off the query:
| Step | From the query |
|---|---|
| select rows of the class | $query->fields->through |
| that belong to the parent | $query->fields->owner equals the parent |
| whose type counts | $query->fields->type holds one of typeValues(), or holds a key of admittedIds() while $query->fields->id holds one of its ids |
| filtered and sorted | $query->filters and $query->sorts, each on LinkRowQuery::rowColumn() of its column |
| ties broken | tiebreak(), each field ascending, after every sort |
| paged | $query->window, counting when $query->countable |
Then $query->member($row) turns each row into the IdentifiedMember it links to,
carrying the row. The type and id rules apply before the filters, the sorts and the page,
so totals and pages stay exact.
A host narrows the types whose rows a scope may hide through one helper, so every data layer narrows alike. It works on a batch of parents, a single parent being a list of one, and the host supplies two things, a key read and an admission check. The steps run in this order:
- Resolve the query with
LinkRowQuery::resolve(). - Call
$query->narrowed($parents, $relation, $keys, $guarded, $admit, $request), with$guardedthe declared types a scope may hide rows of. - The helper reads every parent's stored keys of those types through
$keys, aLinkRowKeysInterface, in one key-only read for the batch. - It calls
$admit($type, $ids)once per guarded type, with the union of that type's keys across the parents, which returns the storage keys the type's provider serves. A guarded type no parent links is narrowed to none without asking. - It narrows each parent's query to the admitted keys that parent holds, with
withAdmitted(), and returns one query per parent in input order. - Run each parent's query through the data layer's
LinkRowQueryInterface.
A data layer implements LinkRowKeysInterface::linkRowKeys($parents, $relation, $types,
$request) beside its link-row query. It returns each parent's distinct storage keys per
requested JSON:API type, keyed by the parent's position in $parents, read from the owner,
type and id fields alone, selecting rows whose owner is one of the parents and whose type
field holds one of LinkRowFields::storedValues($type). InMemoryLinkRows implements it
as the witness. Only the narrowed rows of a type count, and a type narrowed to no keys
drops out. withAdmitted($type, $ids) narrows one type by hand, and a closure
relation narrows the same way through admits().
InMemoryLinkRows applies the same rules over identifiedMembers(), and is the witness
a data layer's query is checked against. It serves every closure relation, since nothing
else can read a closure's rows. LinkRowQuery::inMemoryNotice($relation, $serverPaginator)
returns a message saying so for a closure relation that declares pivot fields, filters,
sorts, a default order or a count, or is paged, for a host to report at warm-up.
Querying the members with a closure¶
When the members are computed rather than stored, such as the values a setting may hold,
and the application already filters and pages them in SQL, declare queriedBy(). Its
closure runs each query itself and returns the page.
Scoping is the closure's job. The library doesn't narrow a queried relation by the scopes of its member types, the way it narrows an
identifiedBy()relation. A member type whose provider hides rows from this caller still shows up if the closure returns it. The closure receives the request, so apply the caller's scope in its own query.
MorphToMany::make('options', ['publishers', 'countries', 'categories'])
->queriedBy(static fn(Target $target, LinkRowQuery $query, JsonApiRequestInterface $request): CollectionResult
=> $options->page($target, $query, $request->getAttribute('user')))
->fields(Str::make('label'))
->withFilters(Where::make('search'), Where::make('advertiser')->integer())
->withSorts(SortByField::make('label'))
->defaultSort(new SortDirective(SortByField::make('label'), false))
->withoutRelatedEndpoint(),
The closure receives the parent, the LinkRowQuery and the request, and returns a
CollectionResult of IdentifiedMember values, each with the row its pivot fields read.
GET /targets/1/relationships/options?filter[search]=north&filter[advertiser]=42&page[size]=25
renders the page it returns, each member's label as its meta.pivot. Its relationship
endpoint accepts every filter and sort the relation declares, not only those on pivot.
columns, and a filter need not compare a column at all: advertiser above names the
context the options are computed for. The usual 400s still apply to a key the relation
doesn't declare and to a value its constraints refuse.
The query carries what the closure applies:
| Member | Holds |
|---|---|
$query->filters |
a FilterDirective per requested filter: key() and its value, a list for a filter that accepts one |
$query->sorts |
a SortDirective per requested sort, $directive->sort->key() and descending, else the relation's default order |
$query->window |
the page to return, always an OffsetWindow, or null for every member |
$query->countable |
whether the page also carries the total |
The closure owns the rest. It orders the members the sorts leave tied, so two pages never
overlap, since the query carries no tiebreak(). It returns the window's page with its
total when the query is countable, else hasMore; WindowExecutor::run() builds either
from closures over the application's query. It also decides which members the caller may
see, as the warning above says. A page that isn't a CollectionResult of IdentifiedMember values, a member of an
undeclared type, a member without the row its stored pivot fields read, or a counted page
with no total throws a \LogicException.
The linkage renders only on the relation's own endpoints. A parent's document shows the
relationship's links and meta and no data, the closure never runs for it, and the
relation can't be included, as if declared cannotBeIncluded(). Declare
withoutRelatedEndpoint() when the member types are related-only, so only the
relationship endpoint is served. MorphToMany::queryMembers($parent, $query, $request)
runs the closure for a data layer, which calls it in place of a LinkRowQueryInterface,
and MorphToMany::countMembers($parent, $request) asks it for a counted empty page when a
parent's document counts the relation. isQueried() says whether a relation was declared
this way; storesIdentifiers() is true for it too.
Writes are unchanged: queriedBy() changes reads only, so fillUsing() owns writes as it
does for identifiedBy(), and the usual cannot*() and read-only settings apply. A write
that needs the current members reads every one of them through the closure, with no
filters and no window, in the default order. That happens for:
- a replace, which keeps the members a scope hides;
- a write of pivot fields, which reads each member's row;
- a relationship write's response, whose linkage echo lists every member.
Keep that cost in mind when a parent has many members.
The closure is only ever handed an OffsetWindow or no window, never a cursor. The
relation's effective paginator, its own paginate() or else the server's default, must
not page by cursor: a CursorPaginator, or a MultiPaginator offering one, fails with
MorphToMany relation "options" declares queriedBy() and is paged by a cursor paginator,
but its closure only ever receives an offset window. Give the relation an offset paginator
with paginate(), such as PagePaginator or OffsetPaginator. Its own paginator fails the
build. The server's fallback is checked at warm-up by
LinkRowQuery::assertOffsetPaginated($relation, $serverPaginator), which a host runs for
every queried relation beside LinkRowQuery::inMemoryNotice().
The build fails with a \LogicException when queriedBy() is declared with:
| Declaration | Problem |
|---|---|
identifiedBy() or identifiedByRows() |
declare one |
withData() |
the linkage renders only on its own endpoints |
cannotBeIncluded() with a predicate |
it can never be included |
withoutLinks(), or neither endpoint exposed |
nothing in a parent's document leads to the linkage |
paginate() with a cursor paginator |
the closure only ever receives an offset window |
No warm-up notice fires for it, since nothing is served in memory.
Writing link rows in a data layer¶
A relation declared with identifiedByRows() has no fillUsing(): declaring one fails the
build, so there is one way its rows get written. A persister asks core for the writes a
relationship write makes and applies them:
$linkage lists the request's members in order as [$type, $id, $pivot], $id the
storage key and $pivot the identifier's meta.pivot. $current is every member the
parent links now as IdentifiedMember values carrying their rows, including those a scope
hides from the client, which $hidden names as [$type, $id] pairs. Pass the hidden
members, always: core alone keeps them through a replace and orders them after the
visible ones, in their current order, so an adapter never positions them itself. Apply the plan's
passes in order, each complete before the next:
| Pass | Holds | Write |
|---|---|---|
deletes |
IdentifiedMember values carrying their rows |
delete each row |
temporary |
LinkRowWrite values for rows that move |
set each row's position past every one in use |
updates |
LinkRowWrite values for existing rows |
set the final position and the written pivot fields |
inserts |
LinkRowWrite values for new rows |
create a row of the through() class with the values |
A LinkRowWrite carries the member and its values, keyed by row field. An insert's
values hold the owner field set to the parent, the type field set to the member's stored
value, LinkRowFields::storedValueFor($type), the id field, and any position and pivot
fields. Set the owner through the row's association on Doctrine, or associate() on
Eloquent.
When the pivot is open, each write also carries the extra members its AdditionalProperties
entry takes, in additional, beside the member's written pivot. After setting a row's values,
call $write->fillAdditional($relation, $row), which hands them to the entry's fillUsing()
hook and returns the row it returns. An existing member that sends only extra members is still
an update.
A replace deletes every current member the linkage leaves out, except a hidden one, and inserts the members it adds. An add inserts the members not yet linked. A remove deletes the linkage's members, never a hidden one. A member the linkage names again keeps its row and takes the pivot fields it sends. Pivot values come from the writable pivot fields, the create-context ones for a new row and the update-context ones for an existing row, each cast by its field and keyed by its row field. A persister converts a value to its storage form, such as a date-time's zone, as it does for any pivot.
InMemoryLinkRows::write($relation, $parent, $plan, $newRow, $storeRows) applies a plan to
rows held on the parent, and fails when a pass would put two rows at one position, so the
witness covers writes as well as reads. $newRow makes a new row, a through() instance
by default. $storeRows receives the parent and the rows as a list and returns the
parent, so a host keeps its own collection type, such as a Doctrine Collection; by
default the list is written to the relation's field.
Laravel's polymorphic relations¶
Each of Eloquent's polymorphic relations has a counterpart here, apart from one:
| Eloquent | Here |
|---|---|
morphTo |
MorphTo, declared with identifiedByColumns() to read its type and id columns |
morphMany, morphOne |
MorphMany, MorphOne, naming the related type's MorphTo |
morphedByMany |
MorphToMany with identifiedByRows(), the link table's owner field naming one owning type |
morphToMany |
not yet: the owner side of its link table is polymorphic, and link rows have no owner type |
Backing and advisory metadata¶
A relation shares the field backing surface and adds one advisory flag for adapters:
| Method | Effect |
|---|---|
storedAs(string $column) |
Read/write the related value from a differently-named domain member than the relationship name. |
computed() |
No backing column; pair with extractUsing() to supply the related value. |
inverseType(string $name) |
Records the inverse relationship name on the related type. Advisory — metadata for adapters / OpenAPI generation. |
Example ids for linkage¶
The OpenAPI operation examples build a relation's linkage
from the related type's Id example. When the related type is not registered on the
server, or its Id declares no example, declare the id on the relation instead:
The related type's own example still wins where it has one. exampleId() is
render-neutral: the runtime never reads it.
The same id is the example of the relation's relationship object schema
(<Type><Relation>Relationship): {"data": {"type": "companies", "id": "co-1"}} for a
to-one, and a list of that one identifier for a to-many. A polymorphic relation shows its
first related type. With no id from either source the schema has no example.
A relation has no value of its own to exemplify, so calling example() on a relation
builder throws a \LogicException pointing at exampleId().
Identifier meta — parent-aware per-relation meta¶
A resource identifier object may carry meta ({ "type": …, "id": …, "meta": … }).
The related resource's own serializer can already contribute meta through its
getMeta(), but that meta describes the resource and renders identically wherever
the resource appears — it has no access to the parent, so it cannot describe the
link: the role a member plays, when an association was formed, an ordering position.
identifierMeta() is the parent-aware hook for exactly that. It declares a resolver
that receives the owning $parent model, the $related object the identifier points
at, and the request, and returns the meta to attach to that identifier — on every
member of a to-many, on a to-one's single identifier, and at the
/relationships/{name} endpoint:
HasMany::make('members', 'users')
->identifierMeta(fn(object $team, object $member, $request): array => [
'role' => $team->roleOf($member),
'joinedAt' => $team->joinedAt($member)->format(\DATE_ATOM),
]),
{
"data": [
{ "type": "users", "id": "7", "meta": { "role": "captain", "joinedAt": "2026-01-01T00:00:00+00:00" } },
{ "type": "users", "id": "9", "meta": { "role": "member", "joinedAt": "2026-02-01T00:00:00+00:00" } }
]
}
The contribution is merged onto whatever the identifier already carries — the
related resource's own meta, including a belongsToMany pivot's meta.pivot — with
the resolver winning on a top-level key collision. Returning [] emits no meta. It
is linkage-only: the related resource object expanded into included is untouched.
Declaring the members¶
The resolver is free-form, so on its own the OpenAPI document can only
describe the identifier's meta as an open object. Pass fields: to say what it returns,
with the field DSL attributes use:
HasMany::make('members', 'users')
->identifierMeta(
fn(object $team, object $member, $request): array => [
'role' => $team->roleOf($member),
'primary' => $team->isPrimary($member),
],
fields: [
Str::make('role')->guaranteed(),
Boolean::make('primary'),
],
),
The fields describe the shape; the resolver still produces the values, already in their
wire form. The projection types each response linkage identifier's meta from them,
under the read rules a pivot follows: every member not hidden or write-only is listed as
present, and null is admitted unless the field is guaranteed(). On a belongsToMany
relation the declared members sit beside pivot in the same meta, so a member named
pivot is refused when the relation is declared. They are read-only, so no request
carries them.
Declared members close the identifier's meta: the projection gives the object
additionalProperties: false, listing pivot among its properties on a pivot-backed
relation, and an adapter's debug check flags a member the resolver returns that the fields do
not name. An AdditionalProperties::make() entry among fields: opens it, typed by its
of() field when one is given. Since the resolver supplies every value, the entry takes no
hook. A relation that passes no fields: keeps an open meta. MorphTo and MorphToMany accept them too, including
those whose linkage renders from stored pairs.
This is distinct from the relationship object's own meta (the meta sibling of
data/links, e.g. a countable relation's meta.total) — that describes the
relationship as a whole, whereas identifierMeta() describes each identifier within
it. A belongsToMany pivot is a specialised, automatic form of identifier meta; reach
for identifierMeta() when the per-link data is not a pivot column.
Conventional links¶
By default every relation emits the spec's conventional self and related
links, built from the owning resource's type + id and the relation's URI segment.
You opt out per relation with withoutLinks():
The URI segment defaults to the relation name; override it with
withUriFieldName() when the endpoint path should differ from the field name:
The endpoints are then /albums/{id}/by and /albums/{id}/relationships/by, and not the
name. The relationship member in relationships stays artist. A host resolving a URL
segment to a relation calls relationAtUriFieldName($segment) on the resource, and builds
its Target with the relation's name().
Links are gated by endpoint exposure: if you suppress a relation's endpoint
(below), the matching link is omitted so a rendered link never points at a 404.
Lazy linkage and withData()¶
Linkage normally requires reading the related value to emit identifiers. For a
lazy storage relation that is an unwanted load just to serialize ids, so a relation
is lazy by default: when the related value is not already loaded, it emits
the relationship object's links only and omits data, rather than triggering a
load.
The default is per relation type, keyed on whether resolving the linkage is free (the identifier is already on the owning side):
| Relation | Default | Why |
|---|---|---|
BelongsTo, MorphTo |
eager (data always rendered) | the foreign key / morph id is on the owning model — the id is already in hand |
MorphTo with identifiedBy() |
always eager | the stored pair is the linkage, so no load-state predicate applies |
MorphToMany with identifiedBy() |
always eager | the stored pairs are the linkage, so no load-state predicate applies |
MorphToMany with queriedBy() |
never on a parent | its closure pages the linkage on its own endpoints only, and withData() fails the build |
HasOne, HasMany, BelongsToMany, MorphToMany |
lazy (links-only until loaded/included) | the key is on the related model, so resolving it is a query (the N+1 risk across a collection) |
Override a lazy relation to eager with withData() — when rendering
identifiers is acceptable, or the related value is reliably preloaded:
The lazy policy is gated by an injected RelationshipLoadStateInterface (the
storage adapter reports load state). Three rules keep the output valid:
- Included wins. An
?included relationship always emitsdata(it has been loaded to be included). - No links and no meta always emits data. A relation that would render neither
links (suppressed via
withoutLinks(), or both endpoints unexposed) nor meta always emits linkage — a relationship object can never be empty{}. - No load-state injected = treated as loaded. With no
RelationshipLoadStateInterfacepresent (the standalone default), the relation emits data as normal.
The OpenAPI document tells a client which to-many relations always carry data: their
relationship object lists data in required when the relation is eager, withData() or
an identified MorphToMany, and no caller can be refused it, or when it renders no links.
See linkage a parent always renders.
Endpoint exposure¶
Each relation exposes two HTTP endpoints by default — the related read
(GET /{type}/{id}/{rel}) and the relationship linkage
(GET|PATCH|POST|DELETE /{type}/{id}/relationships/{rel}). Suppress either one:
| Method | Effect |
|---|---|
withoutRelatedEndpoint() |
The host treats GET /{type}/{id}/{rel} as a 404 and omits the conventional related link. |
withoutRelationshipEndpoint() |
The host treats …/relationships/{rel} as a 404 and omits the conventional self link. |
In both cases the matching link is omitted so a rendered link never points at the
404. See related-endpoints for the endpoints themselves.
Mutation gates¶
Three flags gate what a relationship-mutation request may do (the full replace / add / remove trio):
| Method | Prohibits | Thrown |
|---|---|---|
cannotReplace() |
a PATCH to the relationship endpoint (and a to-one data: null, which is a removal) |
FullReplacementProhibited (403) |
cannotRemove() |
a DELETE from a to-many endpoint, or clearing a to-one (data: null) |
RemovalProhibited (403) |
cannotAdd() |
a POST to a to-many relationship endpoint |
AdditionProhibited (403) |
cannotChangeMembership() |
a to-many replacement listing a different set of members, and every POST and DELETE |
MembershipChangeProhibited (403), and the cannotAdd()/cannotRemove() errors |
All three are allowed by default. See relationship-mutation for how the endpoints map to these gates.
readOnly() and readOnlyOnUpdate() close all three. A relationship mutation
changes an existing resource, so a relation that is read-only on update rejects
PATCH, POST and DELETE on its relationship endpoint with the matching 403,
and its static allowsReplace()/allowsAdd()/allowsRemove() report false, which
drops those verbs from the OpenAPI document. readOnlyOnCreate()
leaves the endpoint open. A readOnly($when) predicate is checked per request: the
verbs stay in the document and a caller the predicate matches gets the 403.
Per-relation security¶
A relation's endpoints are authorized by the parent resource's security by default.
security() lets a single relationship be gated independently — more or less
permissive than the resource it hangs off (a public resource with one privileged
relationship, or a restricted resource with one openly-readable one):
// src/Resource/UserResource.php
BelongsTo::make('billingAccount', 'billing-accounts')
->security(
read: "is_granted('VIEW_BILLING', object)",
mutate: "is_granted('MANAGE_BILLING', object)",
),
readgoverns the related read (GET /{type}/{id}/{rel}) and the relationship linkage read (GET …/relationships/{rel}), and, through the server's relation authorizer, the relationship wherever else it renders. For a caller it denies, a fetched or included resource keeps the relationship'slinksbut renders nodataormeta, and nothing reachesincludedthrough it.mutategoverns relationship mutation (PATCH/POST/DELETE …/relationships/{rel}).
Each value mirrors a resource's security: an authorization expression string
(enforced + documented secured), true (documented secured only — an external
firewall enforces it), false (documented public), or null (the default —
inherit the resource's read/update security). A declared value replaces the
parent's gate for that relation; null falls back to it. The expression is evaluated
by the host's authorization layer, at the endpoints and in the relation authorizer it
gives the server; core stores the declaration and the OpenAPI projection reflects it. See the bundle's authorization guide for how it is enforced.
Includability¶
A relation is includable in a compound document by default. Opt out with
cannotBeIncluded(): a ?include naming it (at any path) is then a
400 InclusionNotAllowed, and it is dropped from the default-include cascade. Its
linkage and self / related links are unaffected.
Pass a closure to decide per request and per model. It receives the model and the
request, and returning true prohibits the include for that model:
HasMany::make('drafts', 'posts')->cannotBeIncluded(
static fn(mixed $author, JsonApiRequestInterface $request): bool
=> $request->getHeaderLine('X-Role') !== 'editor',
),
The closure runs while the document renders, once for each resource carrying the
relation. A requested include it prohibits is the same 400 InclusionNotAllowed, and
a default include it prohibits is dropped for that resource. Since the decision needs
a model, a request that renders no resource carrying the relation, such as an empty
collection, never runs it. The OpenAPI document still lists the relation among the
includable paths, because it is includable for some requests.
This is the per-relation half of the include safeguards; a root-scoped allowed-include-paths whitelist and a maximum include depth are documented under sparse fieldsets and includes.
Write-only relations¶
writeOnly() works on a relation the way it does on an
attribute: a client sets it, the server never shows it.
A create or update can set it in relationships, and its relationship endpoint still
takes PATCH, POST and DELETE under the usual mutation gates.
Everything that would read it back behaves as though the relation weren't declared:
- Every response leaves it out of
relationships. That covers fetches, included resources, related and relationship endpoints, write responses and Atomic Operations results. ?include=approveris a400 InclusionUnrecognized, the error a hidden relation gets.?withCount=approveris a400 RelationshipCountNotAllowed.GET …/approverandGET …/relationships/approverare a404 RelationshipNotExists.- A relationship mutation answers
204 No Contentrather than echoing the linkage.
fields[type]=approver is still a recognised member, so strict mode doesn't reject it,
but it renders nothing, as with a write-only attribute. The relation's static getters
follow suit: isIncludable(), isCountable() and exposesRelatedEndpoint() report
false.
writeOnly($when) takes a request predicate and applies all of the above only to the
requests it returns true for. The static getters then report the permissive value, and
the OpenAPI document describes the readable superset.
Per-relation pagination¶
A to-many relation paginates its related-collection endpoint with paginate():
// src/Resource/AlbumResource.php
HasMany::make('tracks', 'tracks')
->paginate(PagePaginator::make()->withDefaultPerPage(2)),
The host resolves the effective strategy as relation → related resource →
server default: a relation-level paginator wins, otherwise the related
resource's default, otherwise the server's. A to-one relation has no collection
and ignores it. Opt a relation out of pagination entirely with
withoutPagination() — its related collection is then fetched whole (and renders
meta.total unconditionally, see pagination),
regardless of any resolved fallback. See pagination for the
paginators.
The paginator bounds the relationship object too. Wherever the relation's linkage
data renders, included or declared withData(), it holds the first page of the
members, and the relationship object's links carry the other pages. A relation
declared withoutPagination() renders its whole set there as well. See
pagination.
Countable relations and ?withCount¶
A to-many relation can expose its cardinality as meta.total on the relationship
object — the same total semantic endpoint pagination uses. Opt a relation in
with countable(); read it back with isCountable():
// src/Resource/AlbumResource.php
HasMany::make('tracks', 'tracks')
->paginate(PagePaginator::make()->withDefaultPerPage(2))
->countable(),
A client opts into the count per request with the flat, comma-separated
?withCount query parameter — ?withCount=tracks (several relations:
?withCount=tracks,playlists; the reserved _self_ token also counts the primary
collection — see pagination). It is never
dotted (a primary-request parameter, like ?include but un-nested). withCount is
the Countable profile's family, so it is parsed (and
recognized by strict query-parameter validation) only when the client negotiates
that profile's URI in the Accept profile parameter; otherwise it is ignored. When
a request that negotiates the profile names a countable relation —
GET /albums/1?withCount=tracks — its relationship object gains a meta.total:
{
"links": {
"self": "…/albums/1/relationships/tracks",
"related": "…/albums/1/tracks",
"first": "…/albums/1/relationships/tracks?page[number]=1&page[size]=2",
"next": "…/albums/1/relationships/tracks?page[number]=2&page[size]=2",
"last": "…/albums/1/relationships/tracks?page[number]=2&page[size]=2"
},
"meta": { "total": 3 },
"data": [ { "type": "tracks", "id": "1" }, { "type": "tracks", "id": "2" } ]
}
The data is the first page of the relation's two-per-page paginator, and the
count also makes that page counted, so it links last.
With no ?withCount (or none naming this relation) the relationship object
carries no meta key at all. The meta key is exactly total — the same key
the count-based pages emit, so a relationship-object total and an endpoint
pagination total are one consistent semantic.
countable() is the single universal count gate, validated up front and
root-scoped: a ?withCount naming a relation that is not countable() — or
naming a to-one relation, which has no cardinality — is a
400 RelationshipCountNotAllowed (source.parameter: withCount), mirroring
InclusionNotAllowed. A resource that declares no countable relations rejects any
?withCount against it; counting is opt-in.
Counting on a mixed-type response¶
When the primary data mixes types, such as the related endpoint of a MorphToMany
or an action that returns members of several types, a relation name is accepted when
any member type declares it countable. GET /accounts/1/companies?withCount=campaigns
over agencies, advertisers and publishers is valid when agencies or advertisers count
campaigns. Each member renders its own relationships.campaigns.meta.total, read
through RelationshipCountInterface with that member's own relation; a member whose
type has no such countable relation renders without one. Nothing is summed across
members. A name that no member type counts, or counts only where it is write-only for
the request, is still a 400 RelationshipCountNotAllowed. _self_ is unaffected: on
a related endpoint the owning relation's countable() still decides it.
Validation needs to know the member types up front, so the mixed response's
PolymorphicSerializer
must be given them. PolymorphicSerializer::forRelation($relation, $resolver) takes
every registered related type of the relation as a member; a hand-built one passes
the member serializers as its second constructor argument. One built from the
resolving closure alone has no member types and so counts nothing.
Core never computes the count — it is storage-specific (a pushed-down COUNT, a
counted in-memory collection) and batched across a fetched page of parents to
avoid an N+1. The host supplies it through an injected
RelationshipCountInterface
(countRelationship($model, $relation): ?int); with no resolver injected
(standalone core) no meta.total is emitted even for a countable,
?withCount-named relation. The countable flag also drives the related-collection
endpoint's pagination total (a non-countable relation's endpoint paginates
count-free — no total, no last).
Relation-scoped filters and sorts¶
A to-many relation can declare extra filter/sort keys that apply only to
its related-collection endpoint (GET /{type}/{id}/{rel}) — not the primary
collection of the related type. Declare them with withFilters() / withSorts(),
passing the same FilterInterface / SortInterface
value objects a resource exposes:
use haddowg\JsonApi\Resource\Filter\Where;
use haddowg\JsonApi\Resource\Sort\SortByField;
// src/Resource/PlaylistResource.php
HasMany::make('tracks', 'tracks')
->withFilters(Where::make('genre'))
->withSorts(SortByField::make('title')),
The point is scoping. A filter or sort declared on the related resource is
exposed everywhere that type is listed — /tracks and /playlists/1/tracks.
Declaring it on the relation scopes it to that one related-collection endpoint:
the natural home for a contextual filter/sort (ordering a playlist's tracks by
their in-playlist position; a filter only meaningful when listing a user's
posts). The same key is not recognized on the primary /{relatedType}
collection — a request using it there 400s (or simply isn't advertised), exactly
as for any unknown key.
The host merges a relation's withFilters()/withSorts() with the related
resource's own vocabulary, so both apply together on the related endpoint. On a
key clash (the same filter/sort key declared on both the related resource
and the relation) the relation's declaration wins — the more specific scope.
A key in neither set still 400s as an unrecognized parameter.
Scope: the related entity, not the pivot. A relation-scoped filter/sort targets a column on the related entity (the common case) — that works out of the box. A pivot/join-table filter/sort (e.g. a many-to-many
positioncolumn on the join row, not on the related entity) is supported only via a customFilterHandler/SortHandleryou supply — the seam allows it, but the framework does not auto-wire join-table columns. Declare the metadata here and point it at your handler.
Dropping the related type's filter defaults¶
A filter on the related type can declare a default, and
that default applies wherever the type's filters do, so it also narrows every read of a
to-many to that type: its linkage, ?include, ?withCount, the related and
relationship endpoints and a Relationship Queries window. When a relation should list
every member, drop the default there with withoutFilterDefaults():
// TrackResource declares Where::make('explicit')->asBoolean()->default(false)
HasMany::make('tracks', 'tracks')->withoutFilterDefaults('explicit'),
// drops every default the related type declares
HasMany::make('allTracks', 'tracks')->withoutFilterDefaults(),
With keys, only those keys' defaults stop applying. With none, every default the
related type declares does. The filter itself stays, so filter[explicit]=false on
/albums/1/tracks still narrows the members, and /tracks keeps its default. A
default the relation declares on its own withFilters() filter is unaffected.
Each named key must be a filter of the related type that declares a default. A
polymorphic relation needs the key defaulted on at least one of its related types,
since a default may belong to only some of them. The related type's filters are out of
the builder's reach, so RelationFilterDefaultsValidator checks this at warm-up, beside
RelationOrderValidator, and also refuses a dropped default on a custom filter that
doesn't implement HasRemovableDefault. An empty key fails at declaration.
A data layer reads the related type's filters through
RelationFilters::relatedFilters($relation, $relatedResource->allFilters()), which
returns them in order with each dropped default removed, then merges the relation's own
filters as before. RelationFilters::vocabulary($relation, $relatedFilters) does both
steps at once. Read them this way on every path that folds defaults in, so a relation
drops the same defaults however a client reaches its members. The built relation
reports its declaration through DropsFilterDefaultsInterface, which every core
relation implements. The OpenAPI document shows a filter default as the default of its
filter[<key>] parameter's schema, and leaves a dropped one off the relation's related and
relationship endpoints. Relation metadata reports the declaration through
DeclaresDroppedFilterDefaults.
These vocabularies also drive the relationship-queries profile: a client that
negotiates it can filter and sort a relationship's linkage from the primary
request — relatedQuery[<path>][filter][<key>]=… / [sort]=… (shorthand rQ) —
against the same filter/sort keys declared here. See profiles
and the profile specification.
Default read order¶
A to-many relation can declare the order its members are read in when the request
names no sort, with defaultSort(). It takes the same SortDirective list as
AbstractResource::defaultSort(), most
significant first:
use haddowg\JsonApi\Resource\Sort\SortByField;
use haddowg\JsonApi\Resource\Sort\SortDirective;
BelongsToMany::make('tracks', 'tracks')
->fields(Integer::make('position'))
->defaultSort(new SortDirective(SortByField::make('position'), descending: false)),
The order applies wherever the relation's members are read without a requested sort:
the relationship's linkage in a resource document, GET /{type}/{id}/relationships/{rel}
and GET /{type}/{id}/{rel}. A requested sort replaces it entirely, as it does a
resource's default. For this relation it also replaces the related type's own
defaultSort(), which still applies to a relation that declares none.
Each key must name a sort the relation accepts: one of the related type's sorts, a
withSorts() sort or one of its pivot fields. The checks run as early as they can:
| Declaration | Fails |
|---|---|
defaultSort() on a to-one |
at build, with a \LogicException |
defaultSort() on a polymorphic relation declared with none of identifiedByRows(), identifiedBy() and queriedBy(), which takes no sort |
at build |
a key that is no stored pivot field of an identified MorphToMany, or for one declared with queriedBy() no stored pivot field or withSorts() sort |
at build |
| a key none of the relation's sorts answers | at warm-up, from RelationOrderValidator |
RelationOrderValidator needs the related type's sorts, so a host runs it once per
registered resource while it warms its container, beside EagerLoadValidator.
The OpenAPI document writes the declared order as the default of the sort
parameter on the relationship and related endpoints. The related type's default isn't
projected there, because the relation didn't declare it.
Applying it in a data layer¶
A data layer reads the order to apply from RelationSorts::defaultFor($relation,
$resolver): the relation's own default, else its position order,
else the related type's, else []. Apply it
on every read path that returns the relation's members with no requested sort, so the
order is the same however a client reaches them: the two endpoints, document linkage,
?include batching and a Relationship Queries
window. RelationSorts::vocabulary($relation, $resolver) returns the sorts the
relation accepts, and RelationSorts::pivotSorts($relation) the ones its pivot fields
derive. Metadata for the OpenAPI projection reports the relation's own default through
the opt-in DeclaresRelationDefaultSort interface.
Positioned members¶
A to-many relation can keep its members in an order the client sets, with
positionedBy(). It names a stored Integer field that holds each member's position:
a pivot field on a BelongsToMany or an identified MorphToMany, and a field of the
related type on a HasMany.
BelongsToMany::make('tracks', 'tracks')
->fields(Integer::make('position'), Str::make('note'))
->positionedBy('position'),
HasMany::make('tracks', 'tracks')
->positionedBy('trackNumber'), // TrackResource declares Integer::make('trackNumber')->readOnly()
Each kind of write sets positions its own way:
| Write | Positions |
|---|---|
replace, by PATCH or a whole-resource linkage |
each member at its index in the linkage, from 0 |
add, by POST |
new members after the current highest position, in linkage order; members already present keep theirs |
remove, by DELETE |
the removed members go and the gaps stay, nothing is renumbered |
Clients never set a position. A pivot position becomes read-only, so meta.pivot can't
write it and writablePivotFields() leaves it out. A related type's position field
must be declared readOnly() there, so an attribute can't write it. The relation reads
in position order, ascending, unless it declares a default read order
of its own. The OpenAPI document adds nothing: a position the author exposes shows as any
read-only pivot field or attribute does.
The field is checked as early as it can be:
| Declaration | Fails |
|---|---|
a pivot position that isn't a declared, stored Integer pivot field |
at build, with a \LogicException |
a position on the owner, type or id field of an identifiedByRows() relation |
at build |
a related type's position that is missing, computed, not an Integer or writable |
at warm-up, from RelationOrderValidator |
Writing positions in a data layer¶
Core declares the field and never writes it, so a persister writes the positions on every
membership change. For an identified MorphToMany declared with identifiedByRows(), the
link-row write plan already carries every position:
new rows are inserted at their final position and hidden members follow the linkage on a
replace, so the position column needs no default and can be NOT NULL. A relation whose
fillUsing() creates the rows still needs a nullable position the persister fills
afterwards. positionField() names the field, from PositionedRelationInterface,
which every core relation implements. A relation that is a PivotRelationInterface
stores it on the link row, any other on the related row.
A position column is normally unique per owner, and moving members in place collides
with a row that hasn't moved yet. Write in two passes: move every row whose position
changes past every position in use, then to its final position. Positions computes it,
keyed by whatever string identifies a member to the persister:
| Helper | Returns |
|---|---|
Positions::forReplace($linkage) |
each member's index in the linkage |
Positions::forAdd($current, $incoming) |
the positions of the members an add appends |
Positions::plan($current, $target) |
a PositionPlan: the members to delete, then the temporary positions, then the final ones |
Apply a PositionPlan in property order, each pass complete before the next: delete
removed, write temporary, then write final, inserting the members not yet stored at
their final position. A remove passes the current positions less the removed members as
the target, so nothing moves.
RelationSorts::defaultFor() and RelationSorts::ownDefault() return the position order
when the relation declares no default. Its sort is a SortByField on the position column,
which a data layer applies even when the field isn't one of the relation's sorts.
Custom relation hooks¶
When the default reader does not fit — the related value is derived, not a plain property — override the read/write:
| Method | Role |
|---|---|
extractUsing(\Closure $callback) |
Supplies the related domain value(s) instead of reading the property. |
fillUsing(\Closure $callback) |
Writes the parsed input relationship into the domain object instead of the default apply. |
readValue(mixed $model, $request) |
Public accessor: reads the related value(s) without serializing. |
readValue() is what a data layer drives the related and relationship endpoints
with — it hands the related domain value(s) to the related type's provider
without going through the serializer:
The only extractUsing() in the example app is on the favoritable MorphTo
above, where the related object is picked off a discriminated member. Every other
relation uses the default reader — reach for these hooks only when you must.
Next¶
- related-endpoints — the related and relationship read
endpoints,
?include, and paginated related collections. - relationship-mutation —
PATCH/POST/DELETEon relationship endpoints and theModesemantics. - serializers — how a related resource serializes, and the
PolymorphicSerializer. - fields — the shared builder surface a relation inherits.
- pagination — the paginators a relation's collection uses.