Writing

Writing relations

Create, update, attach, detach, sync, toggle and delete related rows in a mutate entry, and write pivot fields with their rules.

The entries under relations write the related rows of a row. The operations that an entry accepts depend on the family of the relation.

app/Rest/Resources/TeamResource.php
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

RelationEntriescreateupdateattachdetachsynctoggledelete
BelongsTo, MorphToOne objectYesYesYesYes
HasOne, HasOneOfMany, MorphOne, MorphOneOfManyOne objectYesYesYesYesWith deletable()
HasMany, MorphManyA listYesYesYesYesWith syncable()With deletable()
BelongsToMany, MorphToMany, MorphedByManyA listYesYesYesYesYesYes
HasOneThrough, HasManyThroughNone
  • The table gives the operations of each family. A relation can withdraw some of them with withoutOperations() or keep only some with onlyOperations(), 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 key there can be a list of keys. A to-one relation takes one object.
  • A custom relation lists its operations in mutationOperations(), as Lomkit\Rest\Fields\MutationOperation cases. A relation that returns [] takes no entry. delete comes from deletable() only: a Delete case in that list is ignored.
  • The details list the operations that each relation accepts, under operations, with ?with=relations.operations.
POST /api/teams/mutate
{
  "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}}
        ]
      }
    }
  ]
}
200 OK
{
  "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

  • create writes a new owner, attach links an existing one, and both set the foreign key of the row. The entry is written before the row that holds it.
  • detach names the current owner of the row, and on a MorphTo its type. Another row, or a detach under a created row, gives The selected mutate.0.relations.author.key is invalid.
  • A MorphTo entry sends type, its morph type, required when the relation has several targets: {"operation": "attach", "type": "book", "key": 2}. Its response entry answers type too.
  • When a resource keeps the morph type column of a MorphTo writable, the column accepts the morph types of its targets only. Declare the morph columns readonly().
  • detach sets the foreign key of the row to null. When that column does not accept null, the entry gives The 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

  • create writes a child with the key of the parent, and on the morph relations its morph type (getMorphClass(), so the morph-map alias).
  • update and detach reach only a child of the parent: a row whose foreign key, and morph type, names the parent. Another row gives The selected mutate.0.relations.tickets.0.key is invalid., and so does any row under a created parent.
  • attach takes a row of another parent and moves it.
  • detach clears 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 gives The mutate.0.relations.tickets.0.key field is prohibited: this relation cannot be detached, its link column does not accept null.
  • attach and create under a HasOne or MorphOne relation 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 detach or its link column does not accept null, the message says what the relation accepts instead:
The relation acceptsMessage
updateThe 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.
neitherThe mutate.0.relations.label field is prohibited: this relation already holds a record and does not detach it.
POST /api/books/mutate
{
  "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(),
POST /api/teams/mutate
{
  "mutate": [
    {
      "operation": "update",
      "key": 101,
      "relations": {
        "tickets": [
          {"operation": "update", "key": 101, "attributes": {"status": "closed"}},
          {"operation": "delete", "key": [103]},
          {"operation": "delete", "key": 102}
        ]
      }
    }
  ]
}
200 OK
{
  "operations": [
    {
      "operation": "update",
      "key": 101,
      "relations": {
        "tickets": [
          {"operation": "update", "key": 101},
          {"operation": "delete", "key": [103]},
          {"operation": "delete", "key": 102}
        ]
      }
    }
  ]
}
  • deletable() exists on HasOne, HasOneOfMany, HasMany, MorphOne, MorphOneOfMany and MorphMany. Without it, at the root of mutate, and on BelongsTo, MorphTo and many-to-many relations, delete gives The selected mutate.0.relations.tickets.0.operation is invalid.
  • key is a key, or a list of keys under a to-many relation. A delete entry takes no attributes and no relations: 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 gives The 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 delete ability of the related resource, as on destroy, and with the link check of detach: the detach ability of the relation, or else update on the parent. A refusal answers 403, and nothing is written.
  • The row goes through the performDelete() of the related resource: a SoftDeletes model is soft deleted, never force deleted, and the model events run.
  • mutatingAll(), mutatedAll() and ResourceMutated see the deletions. The destroying(), destroyed(), destroyingAll() and destroyedAll() hooks of the destroy endpoint 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:

POST /api/teams/mutate
{
  "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"}}
        ]
      }
    }
  ]
}
200 OK
{
  "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 go create entries, update entries of keys that it lists, and delete or detach entries of keys that it does not list. delete needs deletable(), and detach a link column that accepts null.
  • The sync takes key alone, one key or a list. attributes, relations and without_detaching give 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 sync answers the keys that it sent.
  • The details give "sync": "check" on such a relation. Without syncable(), a has-many relation accepts no sync.

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:

POST /api/teams/mutate
{
  "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"}}
        ]
      }
    }
  ]
}
409 Conflict
{
  "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}
  ]
}
  • conflicts holds one item for each sync that leaves out a child: reason is unlisted, path names the sync entry, and key a child that the list neither keeps nor removes.
  • Nothing is written, not even the entries without conflict, and no hook runs.
  • A 409 comes 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 the sync deletes the two tickets that the client did not list, and the request answers 200.
  • 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 403 first, 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.attempts above 1, each attempt runs the check again, see Deadlock retries.

Limits of a synced list

  • A list holds at most rest.limits.sizes.values keys, 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 in config/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:

EntryMessage
A second sync in the listThe mutate.0.relations.tickets.1.operation field is prohibited: a relation takes one sync entry.
An attach next to a syncThe 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 listThe 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 parentThe 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 namesThe 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 syncThe mutate.0.relations.tickets.0.without_detaching field is prohibited.

Many-to-many relations

  • create writes a related row and its pivot row. attach adds pivot rows for existing rows. detach removes them.
  • attach of 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.
  • sync keeps exactly the listed keys among the attached rows, and with "without_detaching": true only adds the missing ones. toggle attaches each listed key that is not attached, and detaches each listed key that is.
  • A relation that does not accept detach takes no toggle, and its sync needs "without_detaching": true. See Many-to-many relations without detach.
  • update attaches the rows that it names and that are not attached, and rewrites the pivot of the attached ones when it sends pivot.
  • sync and toggle answer the keys that they sent. The rows that they detach or attach besides these keys are not listed.
  • update, sync and toggle accept attributes for the related row, with its updatable fields, unless the relation leaves out update: see Relations without update. attach and detach take no attributes: The mutate.0.relations.tags.0.attributes field is prohibited when mutate.0.relations.tags.0.operation is attach.
  • without_detaching on another operation gives The 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, toggle and a sync with "without_detaching": true read only the attached rows that their keys name.
  • A sync without it reads the attached rows of the parent row, and detaches at most rest.limits.totals.entries of them, 1000 by default. A sync that would detach more gives a 422 on its key, and nothing is written. To empty a large relation, send detach entries, or raise the limit:
422 Unprocessable Content
{
  "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 toggle leaves 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 toggle that both detaches and attaches rows, and a sync that both attaches rows and updates the pivot of others, touch the models of $touches twice.
  • The pivot rows go through the pivot persister of the relation, Lomkit\Rest\Mutations\EloquentPivots by default. To write them another way, such as keeping the row of a withdrawn member, declare a persister with persistedBy(). 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"}}
  • create and attach add a pivot row, so they accept the creatable pivot fields, with creationRules(). update, sync and toggle accept the updatable pivot fields, with updateRules(). detach refuses pivot.
  • A readonly() pivot field is refused on every operation. A writeOnly() 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. On update, sync and toggle, it ends with on 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 when pivot is missing too, so a field with creationRules('required') is required on attach: 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 DateTime pivot field with an offset is written in config('app.timezone'), as an attribute is: with UTC, 2026-10-12T08:00:00+02:00 is stored as 2026-10-12 06:00:00. See Dates and times.
  • update, sync and toggle validate with the updatable fields, also when they add a pivot row, because validation runs before the database is read. Use attach to add a row with the creation rules.
  • A pivot field declared virtual(), or with fillUsing() or resolveUsing(), throws InvalidFieldException, and so does a string or a name declared twice.
  • An Enum pivot field reads its enum class from the casts of the pivot class, the class given to using() or Laravel's Pivot.
  • In a search, the pivot of an included row holds the selectable pivot fields only, and filters on tags.pivot.weight accept the filterable ones, see Filters.

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'),
app/Policies/BookPolicy.php
public function attachTag(User $user, Book $book, Tag $tag): bool
{
    return $user->can('update', $book) && ! $tag->archived;
}
  • Without abilities(), a link checks update on the parent.
  • A sync entry with pivot rewrites the pivot of the rows that it keeps attached: it checks the link of each of these rows with the attach ability, or update on the parent. A sync without pivot does not check the rows that it keeps.
  • A declared ability without a policy method is denied.
  • A refused link answers 403 before any write. See Policies.