Reference
Relation helpers
Every relationship helper and modifier.
See Relationships for examples.
Helpers
| Helper | Relationship |
|---|---|
one(?string $resource = null, string|Closure|null $relation = null) | To-one; reads the relation named like the member, or $relation |
many(?string $resource = null, string|Closure|null $relation = null) | To-many |
morph(array $morphs, string|Closure|null $relation = null) | Polymorphic to-one: [Post::class => PostResource::class], first matching class wins |
morphMany(array $morphs, string|Closure|null $relation = null) | Polymorphic to-many |
PostResource::relationship(Closure $value, ?Closure $links = null, ?Closure $meta = null) | Read by a closure (->asCollection() for a to-many); loads only what ->withLoad() declares |
The resource class may be a JsonApiResource, a JsonApiCollection, or a resource of Laravel's native JSON:API
(rendered as a leaf). Without class, on a resource of an Eloquent model, it is guessed from the relation.
Modifiers
| Modifier | Effect |
|---|---|
->links(?Closure $links = null, string|Closure|null $self = null, string|Closure|null $related = null) | links of the relationship object; self: and related: win |
->meta(Closure $meta) | meta of the relationship object; receives the related resource or collection |
->identifierMeta(Closure $meta) | meta of each resource identifier; receives each related resource |
->pivotMeta(array $attributes, string $accessor = 'pivot') | Identifier meta read from the pivot of a BelongsToMany |
->withLoad(bool|string|array $load) | false: never loaded; paths to load, constraints applying to linkage and included |
->whenIncluded(?bool $whenIncluded = null) | data only when included |
->whenLoaded(?string $relation = null) | Rendered only when the relation is loaded; loaded when included |
->whenPivotLoaded(string $table, ?string $accessor = null) | Rendered only when the pivot is loaded |
->linkage(Linkage $linkage) | Linkage::Always, Loaded or Included for this relationship |
->filters(Closure $filters) | Only the related resources passing the rules: fn(Filters $filters) => $filters->can('view')->when(…) |
->can(iterable|string $abilities, array $arguments = [], string $gateClass = Gate::class, ?string $guard = null) | Rendered only when the user has the abilities on the model |
->was(Revision $revision, name: …, schema: $this->one(OldResource::class)) | What the relationship was up to $revision included |
->since(Revision $revision), ->until(Revision $revision) | As for values |
->when(Closure $condition), ->unless(Closure $condition) | Left out when the condition fails; receives (null, $model) |