Resources

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:

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.

Relation types

Relation classEloquent relationOperations in mutate
BelongsTobelongsTocreate, update, attach, detach
HasOnehasOnecreate, update, attach, detach, and delete with deletable()
HasOneOfManyhasOne()->ofMany()same as HasOne
HasManyhasManysame as HasOne, and sync with syncable()
HasOneThroughhasOneThroughnone
HasManyThroughhasManyThroughnone
BelongsToManybelongsToManycreate, update, attach, detach, sync, toggle
MorphOnemorphOnesame as HasOne
MorphOneOfManymorphOne()->ofMany()same as HasOne
MorphManymorphManysame as HasMany
MorphTomorphTocreate, update, attach, detach
MorphToManymorphToManysame as BelongsToMany
MorphedByManymorphedByManysame as BelongsToMany

A relation can accept fewer operations, see Limiting the operations. The details list the operations of each relation under operations, with ?with=relations.operations. See Writing relations for each operation.

Belongs to

A Product belongs to a Category:

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:

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.

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:

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

See 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:

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:

use Lomkit\Rest\Relations\BelongsToMany;

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

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

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

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:

use Lomkit\Rest\Relations\MorphTo;

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

The model keeps one morphTo() method:

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.
{"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.
  • 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.
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'.

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:

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:

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:

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, 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

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:

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

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

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.

Operationdetach()attach()updatePivot()
createthe created row
updatethe named rows not attachedthe named rows attached, when pivot is sent
attachthe named rows
detachthe named rows
syncthe attached rows not named, none with without_detachingthe named rows not attachedthe named rows attached, when pivot is sent
togglethe named rows attachedthe named rows not attached
  • "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:

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:

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.

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
}
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 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.

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:

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):

POST /api/projects/mutate
{
  "mutate": [
    {
      "operation": "update",
      "key": 1,
      "relations": {
        "members": [{"operation": "sync", "key": [2, 3], "pivot": {"role": "writer"}}]
      }
    }
  ]
}
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:

MemberBeforeAfter
Adalead, activelead, withdrawn now
Graceeditor, withdrawn in Februarywriter, active
Linusno rowwriter, active

members now returns Grace and Linus.

Constraints

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

use Lomkit\Rest\Relations\BelongsTo;

BelongsTo::make('category', CategoryResource::class)
    ->requiredOnCreation()
    ->prohibitedOnUpdate(),
ConstraintError when it fails
requiredOnCreation(), requiredOnUpdate()The mutate.0.relations.category field is required.
prohibitedOnCreation(), prohibitedOnUpdate()The mutate.0.relations.category field is prohibited.

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

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():

{"operation": "attach", "key": [1], "relations": {"team": {"operation": "create", "attributes": {"name": "Escalation"}}}}
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:

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() only: neither method takes it, and a deletable() relation keeps it, read-only included.
  • On a HasMany or MorphMany relation, sync comes from syncable() only: neither method takes it, and a syncable() relation keeps it.
  • The details and the OpenAPI document 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:

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.
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.

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:

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 reports a relation that keeps it.

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:

BelongsToMany::make('tags', TagResource::class)
    ->abilities(attach: 'attachTag', detach: 'detachTag'),
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.

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:

HasMany::make('lines', OrderLineResource::class)->deletable(),
{
  "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.

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:

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:

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 with persistedBy(). A custom relation with pivot fields implements Lomkit\Rest\Contracts\PivotRelation, which the Lomkit\Rest\Concerns\Relations\HasPivotFields trait implements.