Skip to content

Fields: the shared builder surface

A field is one entry in a resource's fields() list. Each field describes one member of a resource type — the id, an attribute, or a relationship — and that single declaration drives both directions: how the member is serialized out of a domain object and how it is hydrated back into one. This page documents the fluent surface that every attribute field builder inherits from Resource\Field\AbstractFieldBuilder. Each concrete field type (field types) adds only its type-specific delta on top.

use haddowg\JsonApi\Resource\Field\Id;
use haddowg\JsonApi\Resource\Field\Str;

public function fields(): array
{
    return [
        Id::make(),
        Str::make('title')->required()->maxLength(200)->sortable(),
    ];
}

Each make() returns a field builder — a mutable object whose fluent methods mutate it and return it, so a field reads as one chained expression. The resource builds each builder into a readonly Field value object before use, and one fields() entry configures serialize and hydrate at once. Autocomplete on the builder shows only authoring methods; the built Field exposes only the consumption surface.

Naming and storage

You always construct a field through its static make() factory, never with new. The first argument is the JSON:API member name; by default that name is also the backing domain-object member.

Method Effect
make(string $name) Constructs the field. The member name is also the default backing column.
storedAs(string $column) Reads/writes a different domain-object member than the JSON:API member name.
computed() Marks the field as having no backing column. Pair with extractUsing() for the read value.
computedUsing(\Closure $cb) One-liner for a derived, read-only attribute: computed() + the value closure + readOnly().
on(string $path) Flattens a scalar attribute from a chain of declared, to-one relations' related model ('author' or 'publisher.country').

The shared field namespace

JSON:API 1.1 puts a resource object's attributes and relationships in one namespace with its type and id. So no attribute or relationship may be named type or id, no name may belong to both an attribute and a relationship, and no name may be declared twice among the attributes or among the relationships, where one of the two would otherwise win without a word. The resource checks this the first time it builds its fields, in allFields(), which every reader of the fields goes through. A breach throws a \LogicException naming the resource class, its type and the name, so an application declaring one fails as it boots or on the first request that touches the type. A name declared twice is named with both declarations, by field class and position in fields(), such as the Str at position 2 and the Integer at position 5. The Id field is the one exception, since it renders as the resource object's id.

The check runs on the declared names, whatever a field's visibility. A hidden() relation still can't share its name with an attribute, nor a hidden() attribute with a relation, and a hidden() field still can't repeat the name of another field of its kind. To show a member only to some requests, declare it once with hidden(when:). To expose a domain property called type, give the field another name and point it at the column with storedAs('type'). The same works for an attribute that reads a column a relationship is named after: Str::make('authorName')->storedAs('author') beside BelongsTo::make('author', 'people') is fine, because the names differ. The rule covers only a resource's own fields. A member of an Obj or Map value, a BelongsToMany pivot field and a declared link's meta member can all be called type or id.

Inside an attribute value the spec reserves two other names. No object an attribute holds may contain a relationships or links member, at any depth. The resource checks every member it can see declared: the children of an Obj or Map, the variant children and discriminator of a OneOf, and the same again for any of those nested inside another. A declared member with either name throws a \LogicException naming the resource class and the member's dotted path, such as address.links. A resource's own fields aren't inside an attribute value, so an attribute or relationship called links or relationships is still allowed.

The check stops at what is declared. An ArrayHash, a nested array handed to an Obj or Map under a key no child declares, a value built in a serializeUsing() hook, or a computedUsing() value for a field that declares no children is free-form, and nothing inspects it while serving. The validation layer does. The bundled JSON:API 1.1 schema rejects a links or relationships member in any object inside an attribute value, at any depth and inside arrays, so the spec-compliance assertion and the optional DocumentValidator flag attributes.address.links built from an ArrayHash. Neither runs in production unless you turn it on, so keeping these names out of a free-form value is still up to the code that builds it.

TrackResource exposes a durationSeconds member backed by a differently named column, and a displayTitle member with no column at all:

// The JSON:API member `durationSeconds` is stored on the domain object's
// `length_seconds` column — the rename round-trips through serialize and hydrate.
Integer::make('durationSeconds')->storedAs('length_seconds'),

// Computed: no backing column, derived on read via extractUsing().
Str::make('displayTitle')
    ->computed()
    ->readOnly()
    ->extractUsing(static fn(mixed $track): string => $track instanceof Track
        ? \sprintf('%d. %s', $track->trackNumber, $track->title)
        : ''),

Derived attributes: computedUsing()

computedUsing(\Closure $cb) is the one-liner for the computed-and-read-only pattern above: it marks the field computed() (no backing column), sets the value closure, and marks it readOnly() on both create and update (a derived value has nothing to write back). The closure receives (mixed $model, $request, string $name) and returns the value, which goes through the field's own cast just as a stored column does: a DateTime formats a \DateTimeInterface, an Integer casts a numeric string, an Obj or OneOf runs its declared children. A value already in wire form passes through unchanged, so a closure returning a formatted date string is not re-parsed. A computed Id is taken as already encoded and never run through its encoder. Use serializeUsing() to own the output with no cast at all. The two lines

Str::make('displayTitle')->computed()->readOnly()->extractUsing($fn),
Str::make('displayTitle')->computedUsing($fn),

are equivalent. The lower-level computed() / extractUsing() / serializeUsing() primitives remain available for cases the sugar does not cover, such as a computed field that is not read-only.

on(string $path) flattens a scalar attribute from a chain of declared, to-one relations' related model — the JSON:API resource carries the value inline while the domain stores it on an associated record. $path is a .-separated chain of relation names: 'author' (single hop) or 'publisher.country' (multi-hop). The value is read from / written onto the final related model in the chain, using the field's own column() ?? name(). Every segment must be a declared, to-one RelationInterface; a segment may be hidden(), the idiomatic "internal association" that backs a flattened attribute without ever rendering as a relationship:

// The book's resource exposes `authorName` inline; it lives on the related
// author. The `author` relation is hidden, so it is not a rendered relationship.
Str::make('authorName')->on('author')->storedAs('name'),
BelongsTo::make('author', 'authors')->hidden(),

// A multi-hop chain: book -> publisher -> country, reading the country's `name`.
Str::make('countryName')->on('publisher.country')->storedAs('name'),
BelongsTo::make('publisher', 'publishers')->hidden(),
  • Read. The chain is walked hop by hop (each hop honouring its relation's column()/storedAs()), the field reads its own column() ?? name() off the final related object, and the normal per-type cast applies. Any intermediate null short-circuits the chain → a null attribute value.
  • Write. The value is written onto the final related model (mutated in place — your ORM's unit of work persists the dirty loaded entity on flush). A flattened attribute never auto-instantiates a related model: writing one when any hop is absent is a 422 (RelatedAttributeOwnerMissing, pointing at /data/attributes/<name>). Flattened attributes hydrate after relationships, so a first-hop relation associated in the same request body is visible. That means one body can re-link the relation and write onto the newly linked model, so before each write core asks the server's relation authorizer, when one is set, whether the caller may write onto that related model. A refusal is a 403 ACCESS_DENIED.
  • Supplied targets. When the server has a to-one target seam, each hop reads the target it supplies, on read and write alike. A hop it supplies as none counts as a null hop.

Every segment is validated fail-loud at boot / container warm-up: an unknown segment, or a to-many segment at any depth, is a developer-facing \LogicException (a to-many is not flattenable — use ?include to materialise a collection).

on() is mutually exclusive with computedUsing() / extractUsing() (a flattened attribute reads its own backing member off the related object). For the host to materialise the chain before serializing, the resource declares it as an eager load automatically — see Eager-loading below.

Accessor resolution order

The backing member is resolved through a framework-agnostic accessor. For a member named genres on an object, the read path tries, in order:

  1. a getGenres() method,
  2. an isGenres() method,
  3. a public genres property;

and the write path tries a setGenres() method, then a public genres property. Plain associative arrays and ArrayAccess objects are addressed by key. You never wire any of this up explicitly — it is the zero-config default. ORM entities with private properties and bespoke accessors are handled by a field's extractUsing() / fillUsing() hooks (below), not by this helper.

Visibility and query eligibility

Method Effect
hidden() Drops the field from output and from hydration entirely.
writeOnly() The inverse direction: accepted on write but never rendered (see below).
notSparseField() Exempts the field from sparse-fieldset (?fields[type]=…) filtering, so it is always emitted.
sortable() Marks the field as sortable; the resource's allSorts() derives a SortByField for it.

hidden() removes the member from both directions. For the opposite asymmetry — a member a client sets but the server never echoes back, a password or an API token — reach for writeOnly(), covered next.

Write-only members

writeOnly() marks a field write-only: it is accepted on write — hydrated on both create and update, and still validated — but never rendered. The member is dropped exactly where sparse-fieldset filtering happens, so it appears on no read (single, collection, included, related) and is absent, not null: a fields[type] parameter that names it cannot resurrect it.

UserResource's password is the worked example:

// users: accepted + validated on write, never rendered — absent, not null.
Str::make('password')->writeOnly(),

A POST carrying password hydrates it into the stored object, but the 201 response (and every later GET) omits the member entirely — no "password" key.

writeOnly() and readOnly() are the two opposite asymmetries and cannot combine: a field that is neither readable nor writable is contradictory, so declaring both throws a \LogicException. Inside a Map, a write-only child is skipped on render just like a top-level write-only field, so it too is absent from the nested object.

A relation can be write-only too. See write-only relations.

Read-only scoping (gates hydration)

A read-only field is still serialized, but is silently skipped during hydration in the matching context — a client value in the request body is ignored, not rejected.

Method Effect
readOnly() Read-only on both create and update.
readOnlyOnCreate() Read-only on create (POST) only.
readOnlyOnUpdate() Read-only on update (PATCH) only.

AlbumResource's averageRating is server-computed: a client value in the write body is dropped, and a freshly created album keeps its domain default.

Decimal::make('averageRating')->readOnly()->nullable(),

Request-aware visibility and writability

hidden(), readOnly()/readOnlyOnCreate()/readOnlyOnUpdate() and writeOnly() each also accept an optional closure that decides the restriction per request — lightweight per-caller control without a security framework. The uniform convention: the closure returns true when the restriction applies.

// Hidden only from a non-admin caller. Model first, request second — the same
// argument order as every other field closure (extractUsing/computedUsing), so you
// never swap order between adjacent declarations.
Str::make('draftNote')->hidden(
    static fn(mixed $model, JsonApiRequestInterface $request): bool
        => $request->getHeaderLine('X-Role') !== 'admin',
),

// Write-gating predicates take only the request — a create has no persisted model.
Str::make('locked')->readOnlyOnUpdate(
    static fn(JsonApiRequestInterface $request): bool
        => $request->getHeaderLine('X-Role') !== 'admin',
),

A closure-declared field is not unconditionally restricted, so the static getters (isHidden(), isReadOnly(), isWriteOnly()) report the permissive value and the OpenAPI schema documents the superset (a sometimes-hidden field still appears; a sometimes-prohibited verb is still exposed). The relation authorization predicates cannotReplace()/cannotRemove()/cannotAdd()/ cannotChangeMembership()/cannotBeIncluded() take the same (mixed $model, JsonApiRequestInterface $request) closure — see relations.

A relation hidden from the caller is absent from its related and relationship reads too: they answer 404 RelationshipNotExists, once the handler calls Server::refuseHiddenRelationRead() after loading the parent. See related endpoints.

On a belongsToMany pivot field, the hidden(when:) predicate receives the related member (the far-side resource whose linkage carries meta.pivot) rather than the join row, and hosts resolve both predicates through readablePivotFieldsFor(). See rendering pivot fields.

Presence (gates validation)

The presence helpers declare whether a member must appear, and whether it may be null. They are validation metadata, scoped by request context. On a PATCH, an absent member means "no change" — so required() and requiredOnCreate() differ only on update.

Method Adds
required() Required on both create and update.
requiredOnCreate() Required on create (POST) only; absent on PATCH means "no change".
requiredOnUpdate() Required when supplied on update (PATCH) only.
nullable() Nullable — the member may be null.
Str::make('title')->required()->maxLength(200),
Date::make('birthDate')->nullable(),

Two axes, not one

Read-only and required look adjacent but gate opposite directions, and they compose:

  • Read-only (readOnly*) gates hydration — the value is skipped if present, or refused with a 403 on a server that rejects read-only attributes.
  • Required (required*) gates validation — the value is demanded if the validation adapter executes it.

A readOnly()->nullable() field is serialized and never accepts a client write. The two helpers never conflict because they act in different phases.

Null on read: guaranteed()

A response can carry null for a field no write had to fill: an optional member a create left out is stored as null and rendered as null. So the OpenAPI read schema types an attribute without null only when the server guarantees a value:

  • every create must supply it: required() or requiredOnCreate(), on a field a create can write (a write that declares nullable() still lets null in);
  • a serializeUsing() / extractUsing() / computedUsing() closure produces it and declares a return type without null (fn($model): int => …). An untyped closure could return anything, so it counts as nullable;
  • the author asserts it with guaranteed().

Everything else admits null on read, including a read-only field and a value flattened through on() (any hop in the chain may be null). Core can't see a column default, a fillUsing() that supplies one, or a timestamp the server always sets, so declare those:

DateTime::make('createdAt')->readOnly()->guaranteed(),
Str::make('status')->guaranteed(),  // the entity defaults it to 'draft'

guaranteed() describes the rendered value only. It changes no validation, and the create and update schemas still follow nullable(). Declared on a field that can render null, it makes the document lie to every client generated from it.

On a field no write can set, nullable() has no write to describe, so it describes the rendered value and the read schema admits null even beside guaranteed(). That holds for every member of a read-only or computed value too, because no write reaches them:

Obj::make('changes')->readOnly()->fields(
    Decimal::make('from')->guaranteed()->nullable(),  // number or null
    Decimal::make('to')->guaranteed(),                // always a number
),

A member is written only by the writes that can set every value around it, so a member of an Obj declared readOnlyOnUpdate() takes its read constraints and its null from the create alone.

A named shape is one component for every field using it, so inside one a guaranteed()->nullable() member admits null on read whichever field uses it.

Deprecation: deprecated()

deprecated() marks a field as one clients should stop using. The field's property in the OpenAPI read schema and in the create and update schemas carries deprecated: true. Nothing else changes: the server still renders, hydrates and validates the field exactly as before, so removing it later is still a breaking change you make on purpose.

Str::make('subtitle')->deprecated()->describedAs('Use `tagline` instead.'),
Obj::make('seo')->fields(
    Str::make('keywords')->deprecated(),
    Str::make('slug'),
),

It works on every field builder, the children of an Obj or Map among them, and on relations. A deprecated relation's property under relationships is marked once the framework integration passes it on, which it does through the relation metadata's DeclaresDeprecatedRelation. Its related and relationship endpoints are left unmarked. A deprecated field that is also sortable() derives a deprecated sort, listed under the sort parameter's x-deprecated-sorts. Say what replaces the field in its description, since deprecated has no room for it.

Enumeration

Every field can constrain its value to (or away from) a fixed set:

Method Adds
in(array $values) In — value must be one of $values.
notIn(array $values) NotIn — value must not be one of $values.
enum(string $enum) In over the backing values of a backed enum's cases, keeping the enum's class.
Str::make('status')->in(['draft', 'published', 'archived']),
Str::make('state')->enum(RunState::class),

Backed enums

A field declared with enum(RunState::class), or with in() over cases of one backed enum, converts between the wire's backing value and the enum's case. An In over the enum inside sequentially() declares it too. When a write meets more than one enum, it hydrates to the first one that applies to it in declaration order, an In inside sequentially() taking the place of the sequentially():

  • A write hydrates the value as RunState::from($value) after validation, so a setter setState(RunState $state) or a property typed RunState takes it as it is, as does a Doctrine column mapped with enumType or an Eloquent attribute with an enum cast. A fillUsing() hook receives the case too. null stays null on a nullable() field.
  • A read renders a case as its backing value. A plain string or int renders as it is, so a model that stores the scalar keeps reading.
  • A list of scalars carrying the enum in each(), as ArrayList::make('states')->each(new In(['running', 'done'], enumClass: RunState::class)), hydrates each element as its case. A list declaring several each() calls hydrates to the first enum among all their items, which is the enum its items schema references. A Union member declared with enum() hydrates the case, and a Map child writes the case onto its own column.
  • A value nested in a JSON column keeps the backing value: a child of an Obj, a OneOf variant or a structured ArrayList element, and each element of a list of unions, as a nested date stays a string. A Union stored in a JSON column stores the backing value through toStoredForm() and reads the case back through fromStoredForm().

In the OpenAPI document, in() over some of an enum's cases references the enum's component, which always lists every case, and narrows it with an enum of the listed values beside the reference. in() over every case, in any order, is the same bare reference enum() gives. Scoped to one write with onCreate() or onUpdate(), the narrowing reaches only that write's schema:

Str::make('state')->enum(RunState::class)
    ->onUpdate(static fn (StrBuilder $field): StrBuilder => $field->in([RunState::Cancelled])),

Reads and creates reference the whole RunState, an update takes only cancelled, and every write still hydrates the case.

A write has to pass every in() and enum() that applies to it, so the values it accepts are the ones they all list. When they list none in common the field fails as it is built, which is when the resource's fields are first read at boot or cache warm-up, with a LogicException naming the field, the write and both lists:

Field "status" allows no value on update: in([draft]) and in([archived]) share none.

A whole-write in() meets one scoped with onCreate() or onUpdate() on that write only, and an onCreate() in() never meets an onUpdate() one, so those two may list different values. The check covers plain values and two different enums alike, the values a sequentially() wraps, each item of an each(), each atLeastOneOf() alternative on its own, and every nested field: Obj and OneOf children, structured list elements, Union members, pivot fields and meta fields. An empty in([]) allows no value on its own, so it fails the same way on the writes it applies to:

Field "status" allows no value on create and update: in([]) allows none.

An in() inside when() is left out, since it applies only when its condition holds.

Bounds are checked the same way. A lower bound above the upper bound of its kind on one write, such as min(10) with max(5), minLength(4) with maxLength(3), minItems() above maxItems() or minProperties() above maxProperties(), fails as the field is built. The strictest bound of each side is compared, and an exclusive bound equal to the other side leaves no value either:

Field "rank" allows no value on create and update: min(10) and max(5) leave none.

On an Integer, and on each item of a list declared of('integer'), bounds that leave no whole number between them fail too, such as exclusiveMin(1) with exclusiveMax(2). A Decimal or a list of numbers keeps the rule above, since a real number falls between:

Field "n" allows no value on create and update: exclusiveMin(1) and exclusiveMax(2) leave no integer.

Fixed date bounds on a Date, DateTime or Time are checked the same way. after() and before() exclude their bound and between() includes both of its own, so after() at or past before(), a between() whose start follows its end, or any mix of them that leaves no instant fails. A bound given as a closure is left out, since it moves with each request. A bound at midnight shows as its date, any other in RFC 3339:

Field "at" allows no value on create and update: after(2026-01-01) and before(2025-01-01) leave none.

Filters are not affected: a filter on an enum field still compares the backing value, which Doctrine and Eloquent both bind against an enum column. The reference in-memory filter and sort handlers read a stored case by its backing value too.

enum() takes a backed enum only, and refuses a pure enum when you declare it, since its cases have no value a request could carry. A value outside the enum is refused by validation before anything converts it. If a value reaches hydration unvalidated, it is refused with a 422 ATTRIBUTE_VALUE_INVALID at its pointer.

To keep the string, as for a property or setter typed string or an Eloquent attribute without an enum cast, add a deserializeUsing() hook, which replaces the conversion:

Str::make('state')->enum(RunState::class)
    ->deserializeUsing(static fn (mixed $value): mixed => $value),

Inside a fillUsing() hook, read $value->value from the case instead.

Context scoping

onCreate() / onUpdate() re-stamp every constraint appended inside the closure with that request context, so you don't repeat the …OnCreate suffix on each call:

Str::make('slug')->onCreate(function (StrBuilder $field): void {
    $field->required()->maxLength(64);
});

Inside onUpdate(), an Str::make('slug')->required() applies on update only, where it means "non-empty when supplied". The closure context wins over the helper's default.

Composition and cross-field rules

These appear on every field. They build up the constraint vocabulary that the optional validation adapter executes; core itself never runs them against data.

Method Effect
constrain(ConstraintInterface ...$c) Attaches constraints directly — the typed escape hatch for rules the helpers don't cover, your own implementations included. Each constraint carries its own context; constrain() does not re-stamp it.
sequentially(ConstraintInterface ...$c) Applies the constraints in order, stopping at the first failure; all must ultimately hold.
atLeastOneOf(ConstraintInterface ...$alt) Passes if the value satisfies at least one alternative.
when($condition, $builder) Applies the constraints appended inside $builder only when $condition returns true for the value. The wrapped rules fold into a single When; the condition is opaque PHP, so it does not round-trip to JSON Schema.
compareWith(string $field, Comparison $op) Cross-field comparison: the operator reads <this field> <op> <$field>. $op is a Comparison enum case.

UserResource's passwordConfirm stacks all three of the composition forms in one chain. Unlike the stored-but-write-only password field above, passwordConfirm is computed() because it is a transient confirmation value that is only compared, never persisted. atLeastOneOf()/sequentially()/when() take constraint value objects directly (from the constraint vocabulary), the same way each(new MinLength(1)) does in field types:

use haddowg\JsonApi\Resource\Constraint\Comparison;
use haddowg\JsonApi\Resource\Constraint\MinLength;
use haddowg\JsonApi\Resource\Constraint\Pattern;

Str::make('passwordConfirm')
    ->computed()
    ->serializeUsing(fn(): ?string => null)
    ->atLeastOneOf(
        new MinLength(8),
        new Pattern('^.*[0-9].*$'),
    )
    ->when(
        static fn(mixed $value): bool => $value !== null && $value !== '',
        static function (StrBuilder $field): void {
            $field->minLength(8);
        },
    )
    ->compareWith('password', Comparison::EqualTo),

compareWith is directional. The album pair reads availableUntil > availableFrom — this field is the left operand:

Date::make('availableUntil')
    ->nullable()
    ->compareWith('availableFrom', Comparison::GreaterThan),

See validation for the full constraint vocabulary and the create/update context model, and field types for the per-type helpers (minLength, min, before, …) that wrap these same constraints.

The four hooks

When the accessor and per-type casting aren't enough for a single member, replace part of its read or write path with a closure. Two hooks customise reading, two customise writing — reach for them before dropping to a whole-resource custom serializer / hydrator.

Hook Closure signature Replaces
serializeUsing($fn) fn(mixed $model, JsonApiRequestInterface $request, string $name): mixed The full read path (accessor + cast). On an Obj, Map or ArrayList it also takes ?NestedFieldset $fieldset, the selected keys.
extractUsing($fn) fn(mixed $model, JsonApiRequestInterface $request, string $name): mixed The raw read; the field's per-type cast still applies. On an Obj or Map it also takes ?NestedFieldset $fieldset, the selected keys.
deserializeUsing($fn) fn(mixed $value, array $data): mixed The per-type cast on hydration, including an enum() field's conversion to its case. Not on an Obj, Map, OneOf, Id, a relation or an AdditionalProperties meta entry.
fillUsing($fn) fn(mixed $model, mixed $value, array $data, string $name): mixed The full write path; return the model (or null to keep it unchanged). Not on an Id.

A hook only ever receives the model your provider loaded, so its $model parameter may take the type you know it has: a class such as fn(Track $track), array for a model held as a row, a nullable type, or mixed. PHPStan accepts each one and checks the closure's body against it. The hooks that decide per model whether a member is hidden, a relation is guarded, or a declared link renders take a typed model the same way. $value in deserializeUsing and fillUsing may take the type the field's validation guarantees, as the next section lists.

An Obj, Map or OneOf writes its value through its children, so its builder has no deserializeUsing(). Convert a key with a hook on the child that declares it, or take the whole value with fillUsing(). The Id is written from data.id by its own policy, so its builder has neither write hook: use encodeUsing() when the wire id differs from the storage key, and generated() or generateUsing() to mint one, as ids describes. A relation writes linkage, not a value to convert, and an AdditionalProperties meta entry hands its members to fillUsing() cast by of(), so neither builder has deserializeUsing() either: write the linkage or the members in fillUsing().

On read, serializeUsing wins over extractUsing; on write, fillUsing wins over deserializeUsing. The split matters: extractUsing lets per-type casting finish the job, and on an Obj, Map, OneOf, structured ArrayList or Union the declared shape renders its value and sets the read schema, dropping a key the field doesn't declare. serializeUsing owns the value outright and leaves the read schema open (it is the place to null a computed transient on read, as passwordConfirm above does). To suppress a stored member from output entirely, prefer writeOnly() — it drops the member rather than rendering it as null.

Typing the written value

The adapters check each written value's JSON type before hydrating it, and core puts a number in the type its field documents first, so every field builder knows what its write hooks receive. A typed $value passes PHPStan where the check guarantees that type, and a wrong one fails, such as int on a Str:

Str::make('title')->fillUsing(static fn (Track $track, string $value): Track => $track->retitle($value)),
Integer::make('plays')->deserializeUsing(static fn (int $value): int => \max(0, $value)),
Str::make('note')->nullable()->fillUsing(static fn (Track $track, ?string $value): Track => $track->annotate($value)),
Field $value
Str and its facades (Email, Url, Uuid, Slug, Ip), DateTime, Date, Time string
Integer int, a whole number written as 5.0 included
Decimal float, an integer written as 5 included
Boolean bool
ArrayList list<string>, or by of(): list<int> for integer, list<float> for number, list<bool> for boolean, list<array<array-key, mixed>> for an Obj or OneOf, and a list of a union's member types for a Union
Obj, Map, OneOf array<string, mixed>
Obj with additionalProperties(), ArrayHash array<array-key, mixed>, since PHP decodes a numeric key as an int
Union string\|int\|float\|bool\|list<mixed>

A Decimal's float holds every whole number up to 2^53, 9,007,199,254,740,992, and loses precision above it before validation or a hook sees the value. An exact or a large decimal belongs in a Str with a pattern(), as field types describes.

The value widens with what the declaration lets a write carry:

  • nullable() adds null, and so does constrain() with a Nullable or When.
  • enum(), and in() over cases of a backed enum, add the enum. A top-level field's fillUsing() receives the case and a nested child's the backing value, so the hook takes RunState|string. An ArrayList's each() with such an In adds a list of cases.
  • deserializeUsing() makes it mixed for a fillUsing() declared after it.

onCreate(), onUpdate() and when() add what their closure declares, read from the builder it returns: after ->onCreate(fn (StrBuilder $field) => $field->nullable()) the hook takes ?string. An enum(), an enum in() or a deserializeUsing() declared inside onCreate() converts only a create's value, and one inside onUpdate() only an update's. The other write gets the value as sent unless the field declares its own conversion for it, so after ->onCreate(fn (StrBuilder $field) => $field->enum(RunState::class)) the hook takes RunState|string: the case on a create, the string on an update. when() scopes only validation: an enum declared inside it adds the enum to the type though no write converts, and a deserializeUsing() inside it runs on every write. PHPStan can't see what a closure that returns nothing declared, so after one the value is mixed. Return the builder from the closure, or take mixed in the hook and narrow it there.

These scope types are exact on PHPStan 2.3.2 and later. Earlier 2.x releases report no error on them but infer a narrower value in some cases: 2.0.0 to 2.1.2 miss an enum() or a deserializeUsing() returned from the closure, and 2.1.5 to 2.3.1 miss a deserializeUsing() and a closure that returns nothing. On those releases, type the hook's value yourself.

A builder carries its type from left to right, so declare these before the hook: a nullable() written after fillUsing() does not reach the closure PHPStan already checked.

Some values stay mixed whatever the builder carries. A when() closure's condition value does, since a validator asks it before the type check runs, and so do a relation's hooks, whose values are linkage rather than a typed attribute. A builder you construct yourself, or subclass without forwarding its template, takes mixed too. It is static typing only: nothing changes at runtime.

Worked example: a computed read and a renamed column

TrackResource is the most instructive declaration. displayTitle is computed() (no column) and readOnly(), with its value assembled across two real columns purely on read via extractUsing(); durationSeconds is a plain field whose column is renamed with storedAs(), so the rename round-trips transparently through serialize and hydrate without a hook at all:

final class TrackResource extends AbstractResource
{
    public static string $type = 'tracks';

    public function fields(): array
    {
        return [
            Id::make(),
            Str::make('title')->required()->sortable(),
            Integer::make('trackNumber')->min(1)->sortable(),
            Integer::make('durationSeconds')->storedAs('length_seconds'),
            // …
            Str::make('displayTitle')
                ->computed()
                ->readOnly()
                ->extractUsing(static fn(mixed $track): string => $track instanceof Track
                    ? \sprintf('%d. %s', $track->trackNumber, $track->title)
                    : ''),
            // …
        ];
    }
}

The single-field hooks are the right tool for one member's quirk. When the whole read or write path needs hand-writing — a request-dependent attribute set, say — drop to a custom serializer or hydrator instead. The example's TrackSerializer is registered as a read override for exactly that reason, while the resource above still hydrates writes.

Every on() attribute's backing relation chain is eager-loaded on every read — a load-not-render hint, distinct from ?include (which renders into included) — so the final related model is materialised before the flattened value is read. The dedup set of every on() chain (in field order) is exposed via the DeclaresEagerLoadsInterface::eagerLoadRelationshipPaths() capability (which AbstractResource implements):

Str::make('authorName')->on('author')->storedAs('name'),
Str::make('countryName')->on('publisher.country')->storedAs('name'),
// eagerLoadRelationshipPaths() => ['author', 'publisher.country']

A multi-hop chain ('publisher.country') is walked segment by segment, batch-loaded across the targets the previous level loaded (the same level-walk ?include uses) — O(depth) queries, never per-row. Because every segment is to-one, eager-loading never flips a relationship's linkage rendering, so the document is unchanged. The core library only declares the eager set; the host data layer executes the loading and excludes it from included — an eager load changes the query plan, never the document. Because the set is author-declared, a host may bypass the client-include safeguards (depth cap, allowed-paths, cannotBeIncluded) for it.

The eager set is validated at boot (fail loud)

The eager set is checked at container warm-up — so a mistake fails at cache:clear / deploy, not as a runtime 500. EagerLoadValidator walks every segment of every on() chain across types and throws a \LogicException when:

  • a segment names no declared relation (a typo — it would otherwise silently no-op); or
  • a segment is a to-many relation. on() flattens a single scalar from a to-one chain, so a to-many at any depth — including an ancestor in a dot-path, not just the leaf — is not flattenable. Use ?include to materialise a collection instead.

A segment may be hidden() (the internal-association idiom) or visible — both pass, because the chain is to-one. A polymorphic (MorphTo) or inventory-less segment whose next type cannot be resolved to a single relation-declaring serializer is left unwalked (skipped), not thrown — matching the include walk.

Relationships are fields too

A relationship is declared in the same fields() list and produces the resource object's relationships member. Relations inherit this shared surface (presence, read-only scoping, context) and add their own linkage-shaped helpers. The example's BelongsTo::make('album', 'albums') and HasMany::make('tracks', 'tracks') sit alongside the attribute fields above. See relations for the relation field types and how the server registry resolves the related resource.

Next

  • Field types — the per-type delta for each concrete field (Str, Integer, DateTime, Map, ArrayList, …).
  • Relations — relationship field types (BelongsTo, HasMany, MorphTo, …) and the registry.
  • Resources — how fields() drives the serialize and hydrate walks, id generation, and registration.
  • Validation — the constraint vocabulary and the create/update context model the presence and composition helpers feed.
  • OpenAPI generation — how a field projects to a schema, and the describedAs() / example() authoring surface that shapes it.