Writing relations
The entries under relations write the related rows of a row. The operations that an entry accepts depend on the family of the relation.
use Lomkit\Rest\Fields\Integer;
use Lomkit\Rest\Fields\Text;
use Lomkit\Rest\Relations\BelongsTo;
use Lomkit\Rest\Relations\BelongsToMany;
use Lomkit\Rest\Relations\HasMany;
public function relations(): array
{
return [
BelongsTo::make('company', CompanyResource::class),
HasMany::make('tickets', TicketResource::class)->deletable(),
BelongsToMany::make('members', UserResource::class)->pivotFields([
Text::make('role')->creationRules('required'),
Integer::make('weight')->nullable(),
]),
];
}
Operations by relation family
| Relation | Entries | create | update | attach | detach | sync | toggle | delete |
|---|---|---|---|---|---|---|---|---|
BelongsTo, MorphTo | One object | Yes | Yes | Yes | Yes | |||
HasOne, HasOneOfMany, MorphOne, MorphOneOfMany | One object | Yes | Yes | Yes | Yes | With deletable() | ||
HasMany, MorphMany | A list | Yes | Yes | Yes | Yes | With syncable() | With deletable() | |
BelongsToMany, MorphToMany, MorphedByMany | A list | Yes | Yes | Yes | Yes | Yes | Yes | |
HasOneThrough, HasManyThrough | None |
- The table gives the operations of each family. A relation can withdraw some of them with
withoutOperations()or keep only some withonlyOperations(), see Limiting the operations. - An operation that the relation does not take gives
The selected mutate.0.relations.products.0.operation is invalid. - A to-many relation takes a list of entries, and
keythere can be a list of keys. A to-one relation takes one object. - A custom relation lists its operations in
mutationOperations(), asLomkit\Rest\Fields\MutationOperationcases. A relation that returns[]takes no entry.deletecomes fromdeletable()only: aDeletecase in that list is ignored. - The details list the operations that each relation accepts, under
operations, with?with=relations.operations.
{
"mutate": [
{
"operation": "update",
"key": 1,
"relations": {
"company": {"operation": "attach", "key": 4},
"tickets": [
{"operation": "create", "attributes": {"title": "Printer jam"}},
{"operation": "update", "key": 12, "attributes": {"status": "closed"}},
{"operation": "detach", "key": 13}
],
"members": [
{"operation": "attach", "key": [7, 8], "pivot": {"role": "agent"}},
{"operation": "sync", "key": [9], "without_detaching": true, "pivot": {"weight": 2}}
]
}
}
]
}
{
"operations": [
{
"operation": "update",
"key": 1,
"relations": {
"company": {"operation": "attach", "key": 4},
"tickets": [
{"operation": "create", "key": 31},
{"operation": "update", "key": 12},
{"operation": "detach", "key": 13}
],
"members": [
{"operation": "attach", "key": [7, 8]},
{"operation": "sync", "key": [9]}
]
}
}
]
}
Owner relations: BelongsTo and MorphTo
createwrites a new owner,attachlinks an existing one, and both set the foreign key of the row. The entry is written before the row that holds it.detachnames the current owner of the row, and on aMorphToitstype. Another row, or adetachunder a created row, givesThe selected mutate.0.relations.author.key is invalid.- A
MorphToentry sendstype, its morph type, required when the relation has several targets:{"operation": "attach", "type": "book", "key": 2}. Its response entry answerstypetoo. - When a resource keeps the morph type column of a
MorphTowritable, the column accepts the morph types of its targets only. Declare the morph columnsreadonly(). detachsets the foreign key of the row tonull. When that column does not accept null, the entry givesThe mutate.0.relations.team.key field is prohibited: this relation cannot be detached, its link column does not accept null.See Link columns that do not accept null.
Child relations: HasOne, HasMany and the morph forms
createwrites a child with the key of the parent, and on the morph relations its morph type (getMorphClass(), so the morph-map alias).updateanddetachreach only a child of the parent: a row whose foreign key, and morph type, names the parent. Another row givesThe selected mutate.0.relations.tickets.0.key is invalid., and so does any row under a created parent.attachtakes a row of another parent and moves it.detachclears the foreign key of the child, and the morph type on the morph relations. When the foreign key or the morph type does not accept null, the entry givesThe mutate.0.relations.tickets.0.key field is prohibited: this relation cannot be detached, its link column does not accept null.attachandcreateunder aHasOneorMorphOnerelation give a 422 while the parent already has a related row:The mutate.0.relations.loan field is prohibited: this relation already holds a record. Detach it first.Detach the current row in an entry written before. The of-many forms take another row.- When the relation cannot detach that row, because it does not accept
detachor its link column does not accept null, the message says what the relation accepts instead:
| The relation accepts | Message |
|---|---|
update | The mutate.0.relations.loan field is prohibited: this relation already holds a record and does not detach it. Update that record instead. |
delete, with deletable() | ... and does not detach it. Delete it first. |
update and delete | ... and does not detach it. Update that record instead, or delete it first. |
| neither | The mutate.0.relations.label field is prohibited: this relation already holds a record and does not detach it. |
{
"mutate": [
{"operation": "update", "key": 2, "relations": {"loan": {"operation": "detach", "key": 5}}},
{"operation": "update", "key": 2, "relations": {"loan": {"operation": "attach", "key": 7}}}
]
}
These checks run during validation, before any policy, hook or write, in the order of the entries: an entry sees what the entries before it attach, detach, create and delete.
Deleting child rows
A child relation that declares deletable() accepts delete entries: the rows are deleted in the transaction of the mutation, next to the other writes.
HasMany::make('tickets', TicketResource::class)->deletable(),
{
"mutate": [
{
"operation": "update",
"key": 101,
"relations": {
"tickets": [
{"operation": "update", "key": 101, "attributes": {"status": "closed"}},
{"operation": "delete", "key": [103]},
{"operation": "delete", "key": 102}
]
}
}
]
}
{
"operations": [
{
"operation": "update",
"key": 101,
"relations": {
"tickets": [
{"operation": "update", "key": 101},
{"operation": "delete", "key": [103]},
{"operation": "delete", "key": 102}
]
}
}
]
}
deletable()exists onHasOne,HasOneOfMany,HasMany,MorphOne,MorphOneOfManyandMorphMany. Without it, at the root ofmutate, and onBelongsTo,MorphToand many-to-many relations,deletegivesThe selected mutate.0.relations.tickets.0.operation is invalid.keyis a key, or a list of keys under a to-many relation. Adeleteentry takes noattributesand norelations:The mutate.0.relations.tickets.0.attributes field is prohibited when mutate.0.relations.tickets.0.operation is delete.- Each key must name a child of the parent that the
perimeterQuery()of the related resource returns, when the entry is written. Another key givesThe selected mutate.0.relations.tickets.0.key is invalid. - A deleted row that another entry of the request also names gives
The mutate.0.relations.tickets.1.key field has a duplicate value. - Before any write, each row is checked with the
deleteability of the related resource, as ondestroy, and with the link check ofdetach: thedetachability of the relation, or elseupdateon the parent. A refusal answers403, and nothing is written. - The row goes through the
performDelete()of the related resource: aSoftDeletesmodel is soft deleted, never force deleted, and the model events run. mutatingAll(),mutatedAll()andResourceMutatedsee the deletions. Thedestroying(),destroyed(),destroyingAll()anddestroyedAll()hooks of thedestroyendpoint do not run: put a rule that holds on both endpoints in the policy or in a model observer.- Each deleted key counts as one entry toward
rest.limits.sizes.relation_entries:The mutate.0.relations.tickets field goes over the limit of 100 entries, each deleted key counting as one entry.
Syncing child rows
A HasMany or MorphMany relation that declares syncable() accepts a sync entry: the complete list of the children to keep. The sync writes nothing itself. The entries next to it write the changes, each with its own checks, and together they must account for every child that the user can see.
HasMany::make('tickets', TicketResource::class)->deletable()->syncable(),
Team 101 has the tickets 101, 102 and 103. The client keeps 101 and closes it, deletes 102 and 103, and adds a ticket:
{
"mutate": [
{
"operation": "update",
"key": 101,
"relations": {
"tickets": [
{"operation": "sync", "key": [101]},
{"operation": "update", "key": 101, "attributes": {"status": "closed"}},
{"operation": "delete", "key": [102, 103]},
{"operation": "create", "attributes": {"title": "Broken screen", "status": "open"}}
]
}
}
]
}
{
"operations": [
{
"operation": "update",
"key": 101,
"relations": {
"tickets": [
{"operation": "sync", "key": [101]},
{"operation": "update", "key": 101},
{"operation": "delete", "key": [102, 103]},
{"operation": "create", "key": 104}
]
}
}
]
}
- A relation list takes one
sync. Next to it gocreateentries,updateentries of keys that it lists, anddeleteordetachentries of keys that it does not list.deleteneedsdeletable(), anddetacha link column that accepts null. - The
synctakeskeyalone, one key or a list.attributes,relationsandwithout_detachinggive a 422. - Each listed key must be a child of the parent row: another key gives
The selected mutate.0.relations.tickets.0.key is invalid.Under a parent created in the same request, only[]is valid. - The
syncanswers the keys that it sent. - The details give
"sync": "check"on such a relation. Withoutsyncable(), a has-many relation accepts nosync.
A child that the list leaves out
The sync removes nothing on its own: a child leaves the relation only through a delete or detach entry that names it. So a list that misses a child never deletes a row that the client did not see. The request answers 409 instead.
The team now has the tickets 101 to 112. The client read them through an include with a limit of 10, so the row ended with "@more": ["tickets"], and it syncs the ten keys that it read:
{
"mutate": [
{
"operation": "update",
"key": 101,
"relations": {
"tickets": [
{"operation": "sync", "key": [101, 102, 103, 104, 105, 106, 107, 108, 109, 110]},
{"operation": "update", "key": 101, "attributes": {"status": "closed"}}
]
}
}
]
}
{
"message": "The relation has a related row that the sync neither lists nor removes. Read the relation again, without include limits or filters, then send the request again.",
"conflicts": [
{"reason": "unlisted", "path": "mutate.0.relations.tickets.0", "key": 111}
]
}
conflictsholds one item for eachsyncthat leaves out a child:reasonisunlisted,pathnames thesyncentry, andkeya child that the list neither keeps nor removes.- Nothing is written, not even the entries without conflict, and no hook runs.
- A
409comes from a list read through an include that stopped at its limit (@more), a filtered include, or a child that another request added since the read. - To recover, read the relation again without include limits or filters, then send the request again with each child listed or removed. Here,
{"operation": "delete", "key": [111, 112]}next to thesyncdeletes the two tickets that the client did not list, and the request answers200. - Rows outside the
perimeterQuery()of the related resource, and rows that a global scope hides, trashed rows included, do not count.
When the check runs
- After the policies and the version check, and before any write: a refused policy answers
403first, and locks nothing. - In the transaction of the mutation, the package locks the synced parent rows, then reads, through the
perimeterQuery()of the related resource, one child that each list neither keeps nor removes. Syncs of the same parent wait for each other on that lock. - The check holds when it runs. Another writer can still add a child after it, notably on PostgreSQL and on a
MorphMany, whose morph columns have no foreign key. Index the foreign key column of a synced relation. - With
transactions.attemptsabove 1, each attempt runs the check again, see Deadlock retries.
Limits of a synced list
- A list holds at most
rest.limits.sizes.valueskeys, 100 by default:The mutate.0.relations.tickets.0.key field must not have more than 100 items.A parent with more visible children cannot be synced until you raise the limit inconfig/rest.php. See Limits. - Under an entry with a list of parent keys, each listed key must be a child of every parent, so in practice only
[]works. Sync one parent per entry.
Entries next to a sync
These entries give a 422 before any write:
| Entry | Message |
|---|---|
A second sync in the list | The mutate.0.relations.tickets.1.operation field is prohibited: a relation takes one sync entry. |
An attach next to a sync | The mutate.0.relations.tickets.1.operation field must be create, update, delete or detach next to a sync entry. |
An update of a key that the sync does not list | The mutate.0.relations.tickets.1.key field holds a key that the sync entry of the relation does not list. |
A delete or detach of a listed key, in the same list or under another entry of the parent, or an attach of it under another parent | The mutate.0.relations.tickets.1.key field removes or moves a related row that a sync entry of its parent keeps. |
A sync that neither lists nor removes a child that another entry of the request names | The mutate.0.relations.tickets.0.key field neither lists nor removes a related row that another entry of the request names. |
without_detaching on the sync | The mutate.0.relations.tickets.0.without_detaching field is prohibited. |
Many-to-many relations
createwrites a related row and its pivot row.attachadds pivot rows for existing rows.detachremoves them.attachof a row that the parent already holds, or that an earlier entry of the request attaches, gives a 422 under the key of the entry, unless an earlier entry detaches it:The mutate.0.relations.tags.0.key field holds a record that is already attached. Use update or sync to change its pivot.synckeeps exactly the listed keys among the attached rows, and with"without_detaching": trueonly adds the missing ones.toggleattaches each listed key that is not attached, and detaches each listed key that is.- A relation that does not accept
detachtakes notoggle, and itssyncneeds"without_detaching": true. See Many-to-many relations without detach. updateattaches the rows that it names and that are not attached, and rewrites the pivot of the attached ones when it sendspivot.syncandtoggleanswer the keys that they sent. The rows that they detach or attach besides these keys are not listed.update,syncandtoggleacceptattributesfor the related row, with its updatable fields, unless the relation leaves outupdate: see Relations without update.attachanddetachtake noattributes:The mutate.0.relations.tags.0.attributes field is prohibited when mutate.0.relations.tags.0.operation is attach.without_detachingon another operation givesThe mutate.0.without_detaching field is prohibited unless mutate.0.operation is in sync.
Attached rows
update, sync and toggle compare their keys with the attached rows, read before any write through the perimeterQuery() of the related resource. A sync leaves attached the rows outside it.
update,toggleand asyncwith"without_detaching": trueread only the attached rows that their keys name.- A
syncwithout it reads the attached rows of the parent row, and detaches at mostrest.limits.totals.entriesof them, 1000 by default. Asyncthat would detach more gives a 422 on itskey, and nothing is written. To empty a large relation, senddetachentries, or raise the limit:
{
"message": "The mutate.0.relations.tags.0.key field leaves out more than 1000 attached rows, the most that a sync detaches.",
"errors": {
"mutate.0.relations.tags.0.key": ["The mutate.0.relations.tags.0.key field leaves out more than 1000 attached rows, the most that a sync detaches."]
}
}
- An attached row is a row that the Eloquent relation selects, its conditions included. A
toggleleaves attached a row that the pivot table links but that a condition of the Eloquent relation on the related table hides, such as->where('tags.active', true). - Each entry sees what the entries before it attach and detach on the same parent row.
Order of the pivot writes
The pivot rows of an entry are written after the row of its parent is saved, and before the mutated() hook of that row. A sync or toggle writes its deletes, then its inserts, then its pivot updates.
- A
togglethat both detaches and attaches rows, and asyncthat both attaches rows and updates the pivot of others, touch the models of$touchestwice. - The pivot rows go through the pivot persister of the relation,
Lomkit\Rest\Mutations\EloquentPivotsby default. To write them another way, such as keeping the row of a withdrawn member, declare a persister withpersistedBy(). See Pivot persisters for the calls that each operation makes.
Pivot fields
A many-to-many relation declares its pivot columns with typed fields:
use Lomkit\Rest\Fields\DateTime;
use Lomkit\Rest\Fields\Integer;
use Lomkit\Rest\Fields\Text;
BelongsToMany::make('tags', TagResource::class)->pivotFields([
Integer::make('weight')->nullable()->rules('min:0'),
Text::make('added_by')->updatable(false), // written on create and attach only
Text::make('note')->writeOnly(), // written, never returned
DateTime::make('created_at')->readonly(), // returned, never written
]),
{"operation": "attach", "key": 3, "pivot": {"weight": 5, "added_by": "import"}}
createandattachadd a pivot row, so they accept the creatable pivot fields, withcreationRules().update,syncandtoggleaccept the updatable pivot fields, withupdateRules().detachrefusespivot.- A
readonly()pivot field is refused on every operation. AwriteOnly()pivot field is accepted. - Another key gives a 422 under
pivot:The created_at key of the mutate.0.relations.tags.0.pivot field is not writable on create.Onupdate,syncandtoggle, it ends withon update. - Each value is validated under its key,
mutate.0.relations.tags.0.pivot.weight: the base rule of its type,nullable,rules(), and the rules of the operation. The rules run whenpivotis missing too, so a field withcreationRules('required')is required onattach:The mutate.0.relations.tags.0.pivot.weight field is required. - A rule that names another pivot field, such as
required_with:note, compares with that key in the pivot of the same entry. - A
DateTimepivot field with an offset is written inconfig('app.timezone'), as an attribute is: withUTC,2026-10-12T08:00:00+02:00is stored as2026-10-12 06:00:00. See Dates and times. update,syncandtogglevalidate with the updatable fields, also when they add a pivot row, because validation runs before the database is read. Useattachto add a row with the creation rules.- A pivot field declared
virtual(), or withfillUsing()orresolveUsing(), throwsInvalidFieldException, and so does a string or a name declared twice. - An
Enumpivot field reads its enum class from the casts of the pivot class, the class given tousing()or Laravel'sPivot. - In a search, the
pivotof an included row holds the selectable pivot fields only, and filters ontags.pivot.weightaccept the filterable ones, see Filters.
Link checks
Attaching or detaching a row checks the link on the policy of the parent's resource. A relation can name its own abilities:
BelongsToMany::make('tags', TagResource::class)
->abilities(attach: 'attachTag', detach: 'detachTag'),
public function attachTag(User $user, Book $book, Tag $tag): bool
{
return $user->can('update', $book) && ! $tag->archived;
}
- Without
abilities(), a link checksupdateon the parent. - A
syncentry withpivotrewrites the pivot of the rows that it keeps attached: it checks the link of each of these rows with theattachability, orupdateon the parent. Asyncwithoutpivotdoes not check the rows that it keeps. - A declared ability without a policy method is denied.
- A refused link answers
403before any write. See Policies.