Sources and conditions
A descriptor never holds a value. It says where to read one: its source, read on a subject.
The subject
The subject is what a declaration reads: the model of a JsonResource, each item of a list, the value of an object's
source.
| Declaration | Subject of its children |
|---|---|
a resource's toArray() | the resource's model ($this->resource) |
Schema::object([...], 'shippingAddress') | the value of shippingAddress |
Schema::object([...]) | the parent's subject |
Schema::list(Schema::object([...]), 'lines') | each item of lines |
The source
The source is always the last argument of a helper:
| Declaration | Reads |
|---|---|
'title' => Schema::string() | title, the key the field is declared under (its head key, at every revision) |
Schema::int('total_cents') | the key total_cents |
Schema::string('customer.name') | a dotted path; null as soon as a segment is null |
Schema::string(fn ($value, Order $order) => $order->fullName()) | the closure |
A source closure receives ($value, $subject) and may declare fewer parameters. $value is the value of the declared
key when the subject holds it without side effect (an existing offset, an initialized property, a loaded attribute or
relation), null otherwise: computing $value never triggers a lazy load or an accessor.
A key or a path is read as $model->key would be: casts and accessors apply, and an unloaded relation is
lazy-loaded. Guard a relation with whenLoaded().
Schema::string($this->title) reads the key named by the title. Write
Schema::string('title') or a closure. Any other value (an int, a model) throws.Conditions
A condition decides whether a field is rendered at all. A field refused by a condition is omitted (never null)
and never read, so a condition can guard an expensive source.
| Modifier | Keeps the field when |
|---|---|
whenHas(?string $key = null) | the subject has the key (the declared key by default) |
whenLoaded('customer') | the relation is loaded |
when(fn ($subject, $attribute) => ...) | the closure returns true |
unless(fn ($subject, $attribute) => ...) | the closure returns false |
whenHas() and whenLoaded() run first, then when() / unless(), then the source. A condition closure receives
the subject and the key read ('customer.name' for Schema::string('customer.name'), else the declared key):
'invoice_url' => Schema::string(
fn ($value, Order $order) => $order->invoiceUrl(),
)
->when(fn (Order $order) => $order->isPaid()),
A conditional field is optional in the export.
Put conditions on the descriptor rather than using Laravel's native $this->when(), mergeWhen() or
$this->whenLoaded(): those still work, but are invisible to the schema, and the check reports them
(native-condition).
Two closure signatures
| Closure | Signature | When |
|---|---|---|
a source, down:, up: | ($value, $subject) | to read or convert a value |
when(), unless() | ($subject, $attribute) | before the value is read |
Each may declare fewer parameters.