# Relationships

> Declare the Eloquent relations of a resource, their targets, pivot fields and persisters, constraints, link abilities and the operations they accept.

## Declaring relations

`relations()` returns the relations that clients may include, filter on, sort on and write. Each relation names the Eloquent relation method of the model and the **resource** of the related model:

```php
use Lomkit\Rest\Relations\BelongsTo;
use Lomkit\Rest\Relations\BelongsToMany;
use Lomkit\Rest\Relations\HasMany;

public function relations(): array
{
    return [
        BelongsTo::make('category', CategoryResource::class),
        HasMany::make('comments', CommentResource::class),
        BelongsToMany::make('tags', TagResource::class),
    ];
}
```

- The first argument is the name of the relation method on the model. The second is a resource class, never a model class.
- Use the relation classes of `Lomkit\Rest\Relations`, not the Eloquent ones.
- A relation that the resource does not declare is refused everywhere: in `includes`, in filters, in sorts, in aggregates and in `relations` of `mutate`.
- The related resource applies its own fields, its own `perimeterQuery()` and its own policies to the related rows. See [Perimeter](/resources/perimeter).

## Relation types

<table>
<thead>
  <tr>
    <th>
      Relation class
    </th>
    
    <th>
      Eloquent relation
    </th>
    
    <th>
      Operations in <code>
        mutate
      </code>
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        BelongsTo
      </code>
    </td>
    
    <td>
      <code>
        belongsTo
      </code>
    </td>
    
    <td>
      <code>
        create
      </code>
      
      , <code>
        update
      </code>
      
      , <code>
        attach
      </code>
      
      , <code>
        detach
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        HasOne
      </code>
    </td>
    
    <td>
      <code>
        hasOne
      </code>
    </td>
    
    <td>
      <code>
        create
      </code>
      
      , <code>
        update
      </code>
      
      , <code>
        attach
      </code>
      
      , <code>
        detach
      </code>
      
      , and <code>
        delete
      </code>
      
       with <code>
        deletable()
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        HasOneOfMany
      </code>
    </td>
    
    <td>
      <code>
        hasOne()->ofMany()
      </code>
    </td>
    
    <td>
      same as <code>
        HasOne
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        HasMany
      </code>
    </td>
    
    <td>
      <code>
        hasMany
      </code>
    </td>
    
    <td>
      same as <code>
        HasOne
      </code>
      
      , and <code>
        sync
      </code>
      
       with <code>
        syncable()
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        HasOneThrough
      </code>
    </td>
    
    <td>
      <code>
        hasOneThrough
      </code>
    </td>
    
    <td>
      none
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        HasManyThrough
      </code>
    </td>
    
    <td>
      <code>
        hasManyThrough
      </code>
    </td>
    
    <td>
      none
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        BelongsToMany
      </code>
    </td>
    
    <td>
      <code>
        belongsToMany
      </code>
    </td>
    
    <td>
      <code>
        create
      </code>
      
      , <code>
        update
      </code>
      
      , <code>
        attach
      </code>
      
      , <code>
        detach
      </code>
      
      , <code>
        sync
      </code>
      
      , <code>
        toggle
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        MorphOne
      </code>
    </td>
    
    <td>
      <code>
        morphOne
      </code>
    </td>
    
    <td>
      same as <code>
        HasOne
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        MorphOneOfMany
      </code>
    </td>
    
    <td>
      <code>
        morphOne()->ofMany()
      </code>
    </td>
    
    <td>
      same as <code>
        HasOne
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        MorphMany
      </code>
    </td>
    
    <td>
      <code>
        morphMany
      </code>
    </td>
    
    <td>
      same as <code>
        HasMany
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        MorphTo
      </code>
    </td>
    
    <td>
      <code>
        morphTo
      </code>
    </td>
    
    <td>
      <code>
        create
      </code>
      
      , <code>
        update
      </code>
      
      , <code>
        attach
      </code>
      
      , <code>
        detach
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        MorphToMany
      </code>
    </td>
    
    <td>
      <code>
        morphToMany
      </code>
    </td>
    
    <td>
      same as <code>
        BelongsToMany
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        MorphedByMany
      </code>
    </td>
    
    <td>
      <code>
        morphedByMany
      </code>
    </td>
    
    <td>
      same as <code>
        BelongsToMany
      </code>
    </td>
  </tr>
</tbody>
</table>

A relation can accept fewer operations, see [Limiting the operations](#limiting-the-operations). The details list the operations of each relation under `operations`, with `?with=relations.operations`. See [Writing relations](/writing/relations) for each operation.

### Belongs to

A `Product` belongs to a `Category`:

```php
use Lomkit\Rest\Relations\BelongsTo;

BelongsTo::make('category', CategoryResource::class),
```

A `BelongsTo` include loads the one related row of each parent row: it takes no `limit` and no `sorts`. A search can sort on a field of a to-one relation, such as `category.name`.

### Has one and has many

A `User` has one `Address` and many `Post` models:

```php
use Lomkit\Rest\Relations\HasMany;
use Lomkit\Rest\Relations\HasOne;
use Lomkit\Rest\Relations\HasOneOfMany;

HasOne::make('address', AddressResource::class),
HasOneOfMany::make('latestOrder', OrderResource::class),
HasMany::make('posts', PostResource::class),
```

A to-many include returns at most its `limit` rows per parent row, or the `$includeLimit` of the related resource. See [Includes and aggregates](/search/includes-and-aggregates).

`syncable()` lets a `HasMany` or `MorphMany` relation accept a `sync` entry, the complete list of the children to keep. The `sync` writes nothing: the `create`, `update`, `delete` and `detach` entries next to it write the changes, and the request answers `409` when they leave out a child that the user can see:

```php
HasMany::make('lines', LineResource::class)->deletable()->syncable(),
```

See [Syncing child rows](/writing/relations#syncing-child-rows).

### Through relations

A through relation reaches distant rows through an intermediate model, such as the replies of the tickets of a team:

```php
use Lomkit\Rest\Relations\HasManyThrough;
use Lomkit\Rest\Relations\HasOneThrough;

HasOneThrough::make('car', CarResource::class),
HasManyThrough::make('replies', ReplyResource::class),
```

`HasOneThrough` and `HasManyThrough` can be included, filtered and aggregated, but not written. They accept no operation, and `mutate` refuses any entry under them as a whole: `The mutate.0.relations.replies field is prohibited.` Write the distant rows through the intermediate relations instead.

### Many to many

A `Post` belongs to many `Tag` models, through a pivot table:

```php
use Lomkit\Rest\Relations\BelongsToMany;

BelongsToMany::make('tags', TagResource::class),
```

`MorphToMany` and `MorphedByMany` declare the polymorphic forms, and its inverse:

```php
use Lomkit\Rest\Relations\MorphedByMany;
use Lomkit\Rest\Relations\MorphToMany;

MorphToMany::make('tags', TagResource::class),        // on PostResource
MorphedByMany::make('posts', PostResource::class),    // on TagResource
```

### Morph one and morph many

```php
use Lomkit\Rest\Relations\MorphMany;
use Lomkit\Rest\Relations\MorphOne;
use Lomkit\Rest\Relations\MorphOneOfMany;

MorphOne::make('image', ImageResource::class),
MorphOneOfMany::make('latestImage', ImageResource::class),
MorphMany::make('comments', CommentResource::class),
```

These relations write the morph type with `getMorphClass()`: with a morph map, they write the alias.

### Morph to

A `MorphTo` declares every resource that it can load, its **targets**:

```php
use Lomkit\Rest\Relations\MorphTo;

MorphTo::make('labelable', [BookResource::class, ShelfResource::class]),
```

The model keeps one `morphTo()` method:

```php [app/Models/Label.php]
public function labelable(): MorphTo
{
    return $this->morphTo();
}
```

- Each target is keyed by its morph type, the `getMorphClass()` of its model: the morph-map alias, or the class name without a map. A morph map is recommended.
- A declaration with one resource is the one-target case: `MorphTo::make('commentable', PostResource::class)`.
- Each row that a `MorphTo` include returns starts with its type, under the `@type` key, which `morph.type_key` renames in `config/rest.php`.

```json
{"id": 1, "text": "classic", "labelable": {"@type": "book", "id": 1, "title": "Dune"}}
```

- A row whose stored type is not a target of the relation returns `null` for the include.
- An include of a `MorphTo` with several targets sets its search for each type under `types`. A `MorphTo` include takes no `limit` and no `sorts`, and an aggregate cannot go through it. See [Includes and aggregates](/search/includes-and-aggregates).
- A `MorphTo` entry in `mutate` sends `type`, the morph type of its target: `{"operation": "attach", "type": "shelf", "key": 2}`. It is required with several targets.

<note>

Adding a morph map to an existing application needs the stored types migrated, because a stored class name no longer matches an alias: `UPDATE labels SET labelable_type = 'book' WHERE labelable_type = 'App\\Models\\Book'`.

</note>

## Pivot fields

`BelongsToMany`, `MorphToMany` and `MorphedByMany` declare the columns of their pivot table with typed fields. Each pivot field decides which operations write its column, validates the value, and decides whether the value is returned:

```php
use Lomkit\Rest\Fields\DateTime;
use Lomkit\Rest\Fields\Integer;
use Lomkit\Rest\Fields\Text;
use Lomkit\Rest\Relations\BelongsToMany;

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
]),
```

Declare the same columns on the Eloquent relation, so that Eloquent reads them:

```php [app/Models/Post.php]
public function tags(): BelongsToMany
{
    return $this->belongsToMany(Tag::class)
        ->withPivot('weight', 'added_by', 'note')
        ->withTimestamps();
}
```

- `create` and `attach` accept the creatable pivot fields with their `creationRules()`. `update`, `sync` and `toggle` accept the updatable pivot fields with their `updateRules()`. `detach` refuses `pivot`.
- The `pivot` of an included row holds the selectable pivot fields.
- A filter reaches a pivot field through its relation: `tags.pivot.weight`, with the operators of its type.
- A pivot field is a column of the pivot table: a `virtual()` or `inputOnly()` pivot field, or one with `fillUsing()` or `resolveUsing()`, throws `InvalidFieldException`.
- The pivot fields are bound to the pivot class of the relation, the class given to `using()` or Laravel's `Pivot`. An `Enum` pivot field reads its enum class from the casts of that class.

## Pivot persisters

A many-to-many relation writes its pivot rows through a pivot persister. By default, `Lomkit\Rest\Mutations\EloquentPivots` writes the pivot table with the Eloquent relation. `persistedBy()` declares a class of your application that writes them another way, such as a membership that keeps the row of a member who leaves:

```php [app/Rest/Resources/ProjectResource.php]
use App\Rest\Pivots\ProjectMemberships;
use Lomkit\Rest\Fields\Text;
use Lomkit\Rest\Relations\BelongsToMany;

BelongsToMany::make('members', MemberResource::class)
    ->pivotFields([Text::make('role')->nullable()])
    ->persistedBy(ProjectMemberships::class),
```

- `persistedBy()` exists on `BelongsToMany`, `MorphToMany` and `MorphedByMany`.
- The container resolves the class on each write: its constructor can take dependencies, and a deadlock retry gets a new instance.
- A class that does not implement `Lomkit\Rest\Contracts\PivotPersister` throws `InvalidRelationException` when the relation is declared, and a container binding that returns another class throws it when the relation writes: `The BelongsToMany relation [members] cannot be persisted by [App\Rest\Pivots\Memberships]: persistedBy() takes a class that implements Lomkit\Rest\Contracts\PivotPersister.`
- The package keeps what decides whether a write is allowed: validation, the policies and the [link abilities](#link-abilities), the check of an `attach` on a row already attached, the transaction and its retries. The persister writes the pivot rows that the package hands to it.

### The persister contract

```php
namespace Lomkit\Rest\Contracts;

use Lomkit\Rest\Mutations\PivotWrite;

interface PivotPersister
{
    public function attach(PivotWrite $write): void;

    public function detach(PivotWrite $write): void;

    public function updatePivot(PivotWrite $write): void;
}
```

Each call receives a `Lomkit\Rest\Mutations\PivotWrite` that names at least one related row:

<table>
<thead>
  <tr>
    <th>
      Member
    </th>
    
    <th>
      Value
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        parent
      </code>
    </td>
    
    <td>
      The parent model
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        relation
      </code>
    </td>
    
    <td>
      The name of the Eloquent relation method, such as <code>
        members
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        related
      </code>
    </td>
    
    <td>
      The related models
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        pivot
      </code>
    </td>
    
    <td>
      The values of the pivot fields that the entry sends and the operation writes, in their stored form. <code>
        []
      </code>
      
       on <code>
        detach
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        entry
      </code>
    </td>
    
    <td>
      The <code>
        Lomkit\Rest\Mutations\MutationNode
      </code>
      
       of the entry
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        pivots()
      </code>
    </td>
    
    <td>
      A new Eloquent <code>
        BelongsToMany
      </code>
      
       relation of the parent
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        keys()
      </code>
    </td>
    
    <td>
      The keys of the related rows
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        keyPath()
      </code>
    </td>
    
    <td>
      The error key of the entry, such as <code>
        mutate.0.relations.members.0.key
      </code>
      
      , or the path of the entry, <code>
        mutate.0.relations.members.0
      </code>
      
      , on <code>
        create
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        user()
      </code>
    </td>
    
    <td>
      The user that the package checked the policies for, as <code>
        ActionFields::user()
      </code>
      
       gives it, <code>
        null
      </code>
      
       for a guest
    </td>
  </tr>
</tbody>
</table>

A persister that records who linked a row reads `user()` instead of the authentication state:

```php
public function attach(PivotWrite $write): void
{
    $write->pivots()->attach($write->keys(), [...$write->pivot, 'added_by' => $write->user()?->getAuthIdentifier()]);
}
```

The user is an optional last argument of the `PivotWrite` constructor, so code that builds a `PivotWrite` keeps working.

### How each operation is split

The package reads the attached rows, then splits each entry into calls to the persister, in this order: `detach()`, `attach()`, `updatePivot()`. A call is made only when it names rows.

<table>
<thead>
  <tr>
    <th>
      Operation
    </th>
    
    <th>
      <code>
        detach()
      </code>
    </th>
    
    <th>
      <code>
        attach()
      </code>
    </th>
    
    <th>
      <code>
        updatePivot()
      </code>
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        create
      </code>
    </td>
    
    <td>
      
    </td>
    
    <td>
      the created row
    </td>
    
    <td>
      
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        update
      </code>
    </td>
    
    <td>
      
    </td>
    
    <td>
      the named rows not attached
    </td>
    
    <td>
      the named rows attached, when <code>
        pivot
      </code>
      
       is sent
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        attach
      </code>
    </td>
    
    <td>
      
    </td>
    
    <td>
      the named rows
    </td>
    
    <td>
      
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        detach
      </code>
    </td>
    
    <td>
      the named rows
    </td>
    
    <td>
      
    </td>
    
    <td>
      
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        sync
      </code>
    </td>
    
    <td>
      the attached rows not named, none with <code>
        without_detaching
      </code>
    </td>
    
    <td>
      the named rows not attached
    </td>
    
    <td>
      the named rows attached, when <code>
        pivot
      </code>
      
       is sent
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        toggle
      </code>
    </td>
    
    <td>
      the named rows attached
    </td>
    
    <td>
      the named rows not attached
    </td>
    
    <td>
      
    </td>
  </tr>
</tbody>
</table>

- "Attached" means what the Eloquent relation selects, its pivot conditions included, through the `perimeterQuery()` of the related resource, after the earlier entries of the request.
- Under an entry with a list of keys, the persister is called once for each parent row.
- Write each call so that it can run on a row that is already in that state: a `detach` entry may name a row that is not attached.

### Checking what the persister wrote

After `attach()` and `detach()` of a declared persister, the package reads the links through the Eloquent relation, one query per 1,000 keys. A row that is not linked after `attach()`, or still linked after `detach()`, throws `Lomkit\Rest\Exceptions\PivotPersisterException`, and the mutation rolls back. A soft-withdrawal persister on an `everyone` relation that does not declare the pivot condition gives:

```text
The pivot persister [App\Rest\Pivots\ProjectMemberships] detached [1] on the relation [everyone] of [App\Rest\Resources\ProjectResource], but the relation still links them. A withdrawn pivot row must fall outside the pivot conditions of the Eloquent relation, such as ->wherePivotNull('withdrawn_at').
```

`updatePivot()` is not read back, and neither is the default `EloquentPivots`.

### Persisters that keep pivot rows

This section applies only to a persister that keeps the pivot row of a link that it withdraws. A persister that deletes the pivot rows, and the default one, need nothing.

A persister that keeps withdrawn rows declares the matching condition on the Eloquent relation, with `wherePivotNull()`, `wherePivot()` or another pivot condition:

```php [app/Models/Project.php]
public function members(): BelongsToMany
{
    return $this->belongsToMany(Member::class)
        ->withPivot('role')
        ->wherePivotNull('withdrawn_at');
}
```

Without it, a withdrawn row still counts as attached: `attach` refuses it as already attached, `sync` and `toggle` treat it as attached, and the check after `detach()` throws the `PivotPersisterException` above. With it, the relation reads the current members only, in includes, filters and aggregates too.

### Refusing a write

A persister can refuse a write for a reason of your domain. A `ValidationException` answers a `422` with its keys: put the message on `$write->keyPath()`. An `AuthorizationException` answers a `403`. Both roll back the whole mutation.

```php
use Illuminate\Validation\ValidationException;

public function attach(PivotWrite $write): void
{
    if (Member::query()->whereKey($write->keys())->whereNotNull('left_at')->exists()) {
        throw ValidationException::withMessages([$write->keyPath() => 'This member has left the company.']);
    }

    // write the pivot rows
}
```

```json [422 Unprocessable Content]
{
  "message": "This member has left the company.",
  "errors": {
    "mutate.0.relations.members.0.key": ["This member has left the company."]
  }
}
```

The persister runs inside the transaction of the mutation, and a [deadlock retry](/writing/mutate#deadlock-retries) runs it again on a new instance. Send mails, HTTP calls and jobs after the commit, keep the state of the instance safe to run twice, open no transaction of your own, and let exceptions through.

### Example: memberships with a soft withdrawal

A project keeps the pivot row of a member who leaves, with the date in `withdrawn_at`, and gives the row back when the member joins again.

```php [database/migrations/2026_11_11_000000_create_member_project_table.php]
Schema::create('member_project', function (Blueprint $table) {
    $table->foreignId('project_id');
    $table->foreignId('member_id');
    $table->string('role')->nullable();
    $table->timestamp('withdrawn_at')->nullable();
    $table->unique(['project_id', 'member_id']);
});
```

The `members()` relation of the model declares `wherePivotNull('withdrawn_at')`, as above, and the resource declares the persister:

```php [app/Rest/Pivots/ProjectMemberships.php]
namespace App\Rest\Pivots;

use Illuminate\Support\Facades\Date;
use Lomkit\Rest\Contracts\PivotPersister;
use Lomkit\Rest\Mutations\PivotWrite;

class ProjectMemberships implements PivotPersister
{
    public function attach(PivotWrite $write): void
    {
        $pivots = $write->pivots();

        foreach ($write->keys() as $key) {
            $pivots
                ->newPivotStatement()
                ->updateOrInsert(
                    [$pivots->getForeignPivotKeyName() => $write->parent->getKey(), $pivots->getRelatedPivotKeyName() => $key],
                    [...$write->pivot, 'withdrawn_at' => null],
                );
        }
    }

    public function detach(PivotWrite $write): void
    {
        $write
            ->pivots()
            ->newPivotStatementForId($write->keys())
            ->update(['withdrawn_at' => Date::now()]);
    }

    public function updatePivot(PivotWrite $write): void
    {
        $write
            ->pivots()
            ->newPivotStatementForId($write->keys())
            ->update($write->pivot);
    }
}
```

Project 1 has Ada (1) as `lead`, and kept the row of Grace (2), withdrawn in February. A `sync` names Grace and Linus (3):

```json [POST /api/projects/mutate]
{
  "mutate": [
    {
      "operation": "update",
      "key": 1,
      "relations": {
        "members": [{"operation": "sync", "key": [2, 3], "pivot": {"role": "writer"}}]
      }
    }
  ]
}
```

```json [200 OK]
{
  "operations": [
    {"operation": "update", "key": 1, "relations": {"members": [{"operation": "sync", "key": [2, 3]}]}}
  ]
}
```

The package calls `detach()` for Ada, then `attach()` for Grace and Linus, since the relation does not select the withdrawn row of Grace. The pivot table keeps every row:

<table>
<thead>
  <tr>
    <th>
      Member
    </th>
    
    <th>
      Before
    </th>
    
    <th>
      After
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Ada
    </td>
    
    <td>
      <code>
        lead
      </code>
      
      , active
    </td>
    
    <td>
      <code>
        lead
      </code>
      
      , withdrawn now
    </td>
  </tr>
  
  <tr>
    <td>
      Grace
    </td>
    
    <td>
      <code>
        editor
      </code>
      
      , withdrawn in February
    </td>
    
    <td>
      <code>
        writer
      </code>
      
      , active
    </td>
  </tr>
  
  <tr>
    <td>
      Linus
    </td>
    
    <td>
      no row
    </td>
    
    <td>
      <code>
        writer
      </code>
      
      , active
    </td>
  </tr>
</tbody>
</table>

`members` now returns Grace and Linus.

## Constraints

A relation can be required or refused in a mutation, on creation or on update:

```php
use Lomkit\Rest\Relations\BelongsTo;

BelongsTo::make('category', CategoryResource::class)
    ->requiredOnCreation()
    ->prohibitedOnUpdate(),
```

<table>
<thead>
  <tr>
    <th>
      Constraint
    </th>
    
    <th>
      Error when it fails
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        requiredOnCreation()
      </code>
      
      , <code>
        requiredOnUpdate()
      </code>
    </td>
    
    <td>
      <code>
        The mutate.0.relations.category field is required.
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        prohibitedOnCreation()
      </code>
      
      , <code>
        prohibitedOnUpdate()
      </code>
    </td>
    
    <td>
      <code>
        The mutate.0.relations.category field is prohibited.
      </code>
    </td>
  </tr>
</tbody>
</table>

Each constraint takes a boolean or a callback. The callback receives the request and the related resource, `null` on a `MorphTo` with several targets:

```php
use Lomkit\Rest\Http\Requests\RestRequest;
use Lomkit\Rest\Http\Resource;

BelongsTo::make('category', CategoryResource::class)
    ->requiredOnCreation(fn (RestRequest $request, ?Resource $resource): bool => ! $request->user()?->is_staff),
```

A relation that is required on update is required in every `update` entry, and an empty list does not satisfy it.

The update constraints also apply to the `relations` of an `attach`, `detach`, `sync` or `toggle` entry, since such an entry names a stored row. Under a `labelledTickets` relation whose resource declares `team` with `prohibitedOnUpdate()`:

```json
{"operation": "attach", "key": [1], "relations": {"team": {"operation": "create", "attributes": {"name": "Escalation"}}}}
```

```text
The mutate.0.relations.labelledTickets.0.relations.team field is prohibited.
```

The details list the constraints of each relation under `constraints`, with `?with=relations.constraints`.

## Limiting the operations

A relation accepts every operation of its type by default. `withoutOperations()` withdraws some of them, and `onlyOperations()` keeps only the ones it lists:

```php
use Lomkit\Rest\Fields\MutationOperation;
use Lomkit\Rest\Relations\BelongsTo;
use Lomkit\Rest\Relations\BelongsToMany;
use Lomkit\Rest\Relations\HasMany;
use Lomkit\Rest\Relations\MorphToMany;

BelongsTo::make('team', TeamResource::class)->withoutOperations(MutationOperation::Detach),
HasMany::make('lines', LineResource::class)->withoutOperations(MutationOperation::Create, MutationOperation::Detach),
BelongsToMany::make('tags', TagResource::class)->onlyOperations(MutationOperation::Attach, MutationOperation::Sync),
MorphToMany::make('labels', TagResource::class)->onlyOperations(),            // read-only
```

- The relation accepts the operations of `onlyOperations()`, or all its operations without it, less the operations of `withoutOperations()`. The order of the calls does not matter.
- Several `onlyOperations()` calls keep the operations that every call lists. Several `withoutOperations()` calls add up.
- `onlyOperations()` without arguments makes the relation read-only: `mutate` refuses any entry under it, `The mutate.0.relations.labels field is prohibited.` It can still be included, filtered and aggregated.
- An entry with an operation that the relation does not accept gives `The selected mutate.0.relations.tickets.0.operation is invalid.`
- `delete` comes from [`deletable()`](#deleting-child-rows) only: neither method takes it, and a `deletable()` relation keeps it, read-only included.
- On a `HasMany` or `MorphMany` relation, `sync` comes from [`syncable()`](/writing/relations#syncing-child-rows) only: neither method takes it, and a `syncable()` relation keeps it.
- The [details](/digging-deeper/details#relations) and the [OpenAPI document](/digging-deeper/openapi) list the accepted operations only.

The relation checks the operations it is given when it is declared. A `delete` operation, a `sync` operation on a `HasMany` or `MorphMany`, or an operation that the relation does not accept, throws `Lomkit\Rest\Exceptions\InvalidRelationException`:

```text
The HasMany relation [tickets] cannot withdraw the toggle operation: it does not accept it. Withdraw only the operations it accepts [create, update, attach, detach].
The HasMany relation [tickets] cannot keep the delete operation: a relation accepts delete only through deletable(). Declare deletable() instead.
The HasMany relation [tickets] cannot keep the sync operation: a has-many relation accepts sync only through syncable(). Declare syncable() instead.
The HasOneThrough relation [leadSummary] cannot withdraw the detach operation: it accepts no operation.
```

### Many-to-many relations without detach

A many-to-many relation that does not accept `detach`, through either method, keeps its rows attached:

- it does not accept `toggle` either, since a toggle detaches the attached rows that it names. `onlyOperations()` that lists `toggle` without `detach` throws `InvalidRelationException`: `The BelongsToMany relation [tags] cannot keep toggle without detach: a toggle detaches the attached rows that it names. Keep detach too, or leave toggle out.`
- its `sync` needs `"without_detaching": true`. Without it, or with `false`, the entry gives `The mutate.0.relations.tags.0.without_detaching field must be true: this relation does not detach rows.`

```json [POST /api/tickets/mutate]
{
  "mutate": [
    {
      "operation": "update",
      "key": 101,
      "relations": {
        "tags": [{"operation": "sync", "key": [102], "without_detaching": true}]
      }
    }
  ]
}
```

### Relations without update

A relation whose `update` is left out writes its related rows on `create` only:

- `attributes` on a `sync` or `toggle` entry give `The mutate.0.relations.labels.0.attributes field is prohibited when mutate.0.relations.labels.0.operation is sync.`
- `relations` on an `attach`, `detach`, `sync` or `toggle` entry give the same message under `relations`.
- The pivot is still written: an `attach` with `pivot` adds pivot rows, and a `sync` with `pivot` rewrites the pivot columns of the rows that it names.

### The operations belong to the relation

The operations are declared on one relation, not on the link between two models. The inverse relation keeps its own operations: when `Ticket::tags` withdraws `detach`, `Tag::tickets` still detaches rows unless it limits its operations too.

### Link columns that do not accept null

A `detach` sets a column to `null`: the foreign key of a `BelongsTo` in the table of the row, or the foreign key and the morph type of a `HasOne`, `HasMany`, `MorphOne` or `MorphMany` in the related table. When that column does not accept null, the entry gives a `422` on its `key`, before any write:

```text
The mutate.0.relations.team.key field is prohibited: this relation cannot be detached, its link column does not accept null.
```

Withdraw `detach` from such a relation: `rest:resource --generate` and `rest:quick-start` add `->withoutOperations(MutationOperation::Detach)` for you, and [`rest:check`](/digging-deeper/artisan#relations-that-detach) reports a relation that keeps it.

## Link abilities

A mutation that links two rows checks the link on the policy of the parent row. By default, it checks `update` on the parent. Declare the abilities of the relation to check others:

```php
BelongsToMany::make('tags', TagResource::class)
    ->abilities(attach: 'attachTag', detach: 'detachTag'),
```

```php [app/Policies/PostPolicy.php]
public function attachTag(User $user, Post $post, Tag $tag): bool
{
    return $user->team_id === $post->team_id;
}
```

`attach` covers the `create`, `update` and `attach` entries and the rows that `sync` and `toggle` attach. `detach` covers the `detach` entries and the rows that `sync` and `toggle` detach. A declared ability that no policy method answers is denied. See [Policies](/authorization/policies).

## Deleting child rows

A child relation can delete its rows in the same mutation as their parent once it declares `deletable()`. This applies to `HasOne`, `HasOneOfMany`, `HasMany`, `MorphOne`, `MorphOneOfMany` and `MorphMany`:

```php
HasMany::make('lines', OrderLineResource::class)->deletable(),
```

```json
{
  "mutate": [
    {
      "operation": "update",
      "key": 7,
      "relations": {
        "lines": [{"operation": "delete", "key": [102, 103]}]
      }
    }
  ]
}
```

Each key must be a child of the parent row. Each row is checked with the `delete` policy of the related resource and with the `detach` link check, then deleted through the `performDelete()` of the related resource. The hooks of the `destroy` endpoint do not run. The details list `delete` last in the `operations` of a `deletable()` relation. See [Writing relations](/writing/relations#deleting-child-rows).

## Custom relations

A relation class of your application extends one of the package classes. `mutationOperations()` lists the operations that its entries accept, as cases of `Lomkit\Rest\Fields\MutationOperation`. A relation that returns `[]` takes no entry in `mutate`:

```php
use Lomkit\Rest\Fields\MutationOperation;
use Lomkit\Rest\Relations\HasMany;

class AppendOnlyHasMany extends HasMany
{
    public function mutationOperations(): array
    {
        return [MutationOperation::Create];
    }
}
```

`withoutOperations()` and `onlyOperations()` apply on top of `mutationOperations()`. A custom relation whose `mutationOperations()` never listed `update` writes its related rows as before, and one that leaves out `detach` keeps its `sync` and `toggle` as they are.

A custom has-many relation that lists `MutationOperation::Sync` in `mutationOperations()` keeps that `sync`: it links the rows that it names and checks nothing, and the details give it `"sync": "link"`. `syncable()` on such a relation throws `InvalidRelationException`:

```text
The SyncedHasMany relation [tickets] cannot declare syncable(): its mutationOperations() already list sync, which links the rows it names and removes none. Leave sync out of mutationOperations(), or leave syncable() off.
```

The package writes a relation by the class of its Eloquent relation. A relation has no write hook: change a write in the `mutating()` and `mutated()` hooks of the resource. The pivot rows of a many-to-many relation are written before `mutated()` runs: to write them another way, declare a [pivot persister](#pivot-persisters) with `persistedBy()`. A custom relation with pivot fields implements `Lomkit\Rest\Contracts\PivotRelation`, which the `Lomkit\Rest\Concerns\Relations\HasPivotFields` trait implements.
