Getting Started

Upgrade guide

Upgrade to 3.5, 3.4, 3.3, 3.2.3, 3.2.2, 3.2.1, 3.2, 3.1.1, 3.1 and 3.0.1, then the changes from 2.x to 3.0 by area, each with a link to the page that documents it.

Upgrading to 3.5 from 3.4

Version 3.5 adds a feature: instructions declared by their class. Upgrade with composer update lomkit/laravel-rest-api, then go through the checks below.

Check after upgrading

  • Instructions. Move the settings of each instruction into its properties, such as public ?string $name = 'Held by';, and list it by its class. Keep the instance form for an instruction built with arguments or reused with other settings. Then run php artisan rest:check. See Instructions.
  • rest:check. The declarations section counts the instructions that it builds, 4 actions, 2 metrics, 3 instructions built, and the declarations key of rest:check --json gains instructions: a script that reads the report key by key sees it. See Checking the application.

What 3.5 adds

  • instructions() accepts class names next to instances: return [HeldByInstruction::class, UnendedInstruction::make()->meta(['group' => 'dates'])];. The container builds the listed classes, so a constructor can inject services. See Instructions that inject services.
  • The classes are built the first time the resource reads its instructions in a request: a search that sends instructions, at its root, in an include of the resource or in the search of an action or a metric, and /details. A request that reads no instruction, such as a mutation or a search without instructions, builds none, and registering the routes reads no instruction. See When the instructions are built.
  • Reading one instruction builds the whole list of the resource: keep the constructors light and do the work in handle(). Each class is built once per resource definition, that is once per request. The OpenAPI document and rest:check build their own.
  • Instructions have no route, so an instruction listed by its class can still override name() or uriKey().
  • When the instructions are read, InvalidInstructionException refuses a name that is not a class extending Instruction, Instruction::class itself, an abstract class, and a container binding that returns another class, with a message that names the resource. See Declaration checks.
  • rest:check builds every instruction of the resources of the checked controllers and of every resource that their relations reach, since an include can read them. It reports these errors, a constructor parameter that the container cannot resolve and any other error of a constructor in its declarations section, each with the name of the resource. See Actions, metrics and instructions.
  • /details, the OpenAPI document and searches stay the same for a class and the matching instance. Instances still work, and one list can mix both forms.
  • rest:instruction prints the class form to list in the resource: List it in the instructions() of a resource by its class: HeldByInstruction::class.

Upgrading to 3.4 from 3.3

Version 3.4 adds features: actions and metrics declared by their class with their own route key, required reads of input values, and advice for test suites. Upgrade with composer update lomkit/laravel-rest-api, then go through the checks below.

Check after upgrading

  • Cached metric results. The results that cacheFor() keeps are computed again once: the cache key of a metric now holds its uriKey property. See Caching a result.
  • Cached routes. After you change the key or the middleware of an action or a metric, run php artisan route:cache again. Until then, the action or the metric throws InvalidActionException or InvalidMetricException and does not run, where it used to run with the middleware of the cached route. See Cached routes.
  • rest:check. Move the settings of each action and metric into its properties, list it by its class, then run php artisan rest:check. The report adds a declarations section, and rest:check --json a declarations key: a script that reads the report key by key sees it. See Checking the application.

What 3.4 adds

  • actions() and metrics() accept class names next to instances: return [CloseTickets::class, ExportTickets::make()->middleware('throttle:exports')];. An action carries its own configuration in its properties, such as $name, $middleware, $target or $destructive. Registering the routes builds no class, and the container builds it only when it is used, so its constructor can inject services. Instances still work, for an action reused with other settings in several resources. See Defining an action.
  • Actions and metrics have a $uriKey property, which sets the route key apart from the name: public ?string $uriKey = 'end'; on EndAttachmentAction gives /actions/end, and /details keeps the name End Attachment. See Route key and name.
  • When the routes register, InvalidActionException or InvalidMetricException refuses a class that overrides name() or uriKey(), an abstract class, Action::class or Metric::class itself, and a class of the other kind. The other declaration errors of a class throw when it is first built, and rest:check builds every action and metric to report them. See Declaration checks.
  • Each action and metric route records the key and middleware that it was registered with, also through route:cache. An action or a metric, class or instance, that a request or a queued run builds with another key or other middleware throws and does not run.
  • The typed readers of ActionFields and InstructionFields take required: true: $fields->date('last_day', required: true) is a CarbonImmutable for PHPStan, not a ?CarbonImmutable. A null value throws InvalidFieldException: give the input the required rule. See Required reads.
  • rest:action and rest:metric print the class form to list in the resource: List it in the actions() of a resource by its class: CloseTickets::class.
  • In a test suite, Laravel's Illuminate\Foundation\Testing\WithCachedRoutes trait on the base test case keeps the routes of the first test for the following tests, so Rest::resource() no longer runs between tests. With the trait, a route registered after the application booted is matched by URL, but route('name') and the lookups by name or by action can miss it: register such routes in a test case without the trait. See Test suites.

Upgrading to 3.3 from 3.2

Version 3.3 adds features: typed readers for the inputs of actions and instructions, the user in pivot persisters, the model type of actions and instructions, and a checked sync for has-many relations. Upgrade with composer update lomkit/laravel-rest-api, then go through the checks below: two answers gain a key.

Check after upgrading

  • Conflicts. Each item of the conflicts of a 409 has a reason: version on a version conflict, which keeps its path, key and version, and unlisted on a has-many sync. A client that compares a conflict item key by key sees the new key. See Conflicts.
  • Details. /details adds sync to each relation, with relations.operations: replace, link or check, and null when the relation takes no sync. See Relations.
  • Relation classes of your application. A relation subclass that already declares syncable(), isSyncable() or syncsChildren() renames its method. A custom relation that lists MutationOperation::Sync in mutationOperations() keeps its sync, which links the rows that it names and checks nothing.

What 3.3 adds

  • ActionFields and InstructionFields read an input in a given type: string(), integer(), float(), boolean(), date(), enum() and array(), such as $fields->enum('status', Status::class). Each returns the value that the field cast, or null. float() also converts an int or a numeric string, and integer() a string that is exactly an integer. A value of another type throws InvalidFieldException. $fields->reason keeps working. See Typed readers.
  • PivotWrite::user() returns the user that the package checked the policies for, null for a guest, so a pivot persister can record who linked a row without reading the authentication state. See The persister contract.
  • Action and Instruction declare their model as a PHPStan template with a default, @template TModel of Model = Model. /** @extends Action<Invoice> */ narrows handle(), beforeRow() and handleRow(), and /** @extends Instruction<Invoice> */ the query of handle(). A class without @extends gets no new error at any level. See The model of an action.
  • A HasMany or MorphMany relation accepts sync with syncable(). The sync lists the children to keep and writes nothing; the create, update, delete and detach entries next to it write the changes. Before any write, the package checks that they account for every child that the user can see, and answers 409 otherwise: a list read through a cut or filtered include never deletes a row that the client did not see. See Syncing child rows.
  • The OpenAPI document describes the conflicts items as a oneOf of the two shapes, and lists the 409 on a mutation that reaches a syncable() relation.

Changes in 3.2.3

Version 3.2.3 fixes static analysis and a note on route registration, and adds no feature. Upgrade with composer update lomkit/laravel-rest-api.

  • Constructors. PHPStan no longer requires a constructor without arguments on an action, an instruction or a metric: one whose constructor injects a service passes. make() still passes its arguments to the constructor.
  • Inputs as properties. The package ships an extension.neon that lets PHPStan read the inputs of ActionFields and InstructionFields as properties, such as $fields->reason. phpstan/extension-installer includes it. Without it, add vendor/lomkit/laravel-rest-api/extension.neon to the includes of your phpstan.neon. See Static analysis.
  • new static(). A subclass that redefines make() with new static(...) now gets PHPStan's "Unsafe usage of new static()". Add /** @phpstan-consistent-constructor */ on that class.
  • Route registration. Rest::resource() builds the resource through the container, and actions() and metrics() create the actions and metrics, so their constructors run at boot, in every Artisan command, and on every request while the routes are not cached. X::make() calls the constructor with the arguments that it receives: declare an action or a metric that injects services with app(X::class), or, since 3.4, list it by its class. instructions() is read when a search or /details first needs it. See Actions that inject services.

Changes in 3.2.2

Version 3.2.2 fixes a bug and adds no feature. Upgrade with composer update lomkit/laravel-rest-api.

  • Exports and actions. An export through Rest::search(...)->lazy(), or an action on a search with sorts or a limit, no longer fails when an instruction, a scope, or a MorphTo or aliased include decorates the rows with an afterQuery() callback. Before, the keys of the rows were read through the row query, so the callback received the keys instead of the models: a callback typed Illuminate\Database\Eloquent\Collection threw a TypeError and the request answered 500.
  • Reading the keys. The keys are read without the callbacks. The rows loaded by key still run them, once per chunk. See Decorating the rows.

Changes in 3.2.1

Version 3.2.1 fixes a bug and adds no feature. Upgrade with composer update lomkit/laravel-rest-api. Some stored values change:

  • Dates with an offset. A DateTime value with an offset, such as 2026-10-12T08:00:00+02:00, is converted to config('app.timezone') before it reaches the database: in filters, with every operator, between and not between included, in mutate attributes and pivot fields, and in the inputs of scopes, instructions and actions. Before, the offset was dropped: with UTC, a filter compared 08:00:00 and missed the row stored at 06:00:00, and a write stored 08:00:00. See Dates and times.
  • Wall times stored as sent. An application that relied on the wall time being stored as sent now stores other values. Send the time in the application timezone, or override normalize() in a DateTime subclass.
  • What stays the same. A value without an offset is read in the application timezone. A Date value keeps the day as sent. fillUsing() and filterUsing() callbacks, and $entry->attributes in mutating() and mutated(), still receive the value as sent.

Upgrading to 3.2 from 3.1

Version 3.2 adds features: input-only fields, and pivot persisters that write the pivot rows of a many-to-many relation. Upgrade with composer update lomkit/laravel-rest-api, then go through the checks below: a few many-to-many write details change.

Check after upgrading

  • update entries under a many-to-many relation read whether the rows they name are attached, through the perimeterQuery() of the related resource, as toggle does. See Attached rows.
  • toggle keeps a hidden row attached. 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), as its checks expect. It used to detach it.
  • Write order. A many-to-many sync or toggle writes its deletes, then its inserts, then its pivot updates. See Order of the pivot writes.
  • Touches. 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 instead of once.
  • Columns that a hook fills. The attributes that the client sends are written after mutating(): a column that the hook fills must not also be a writable field, or the sent value overwrites the value of the hook. Declare that column readonly(), creatable(false) or updatable(false), or leave it out of fields(). See Columns that a hook fills.

What 3.2 adds

  • inputOnly() declares a field that mutate validates and hands to the hooks without writing it on the model: Text::make('delivery_address')->inputOnly()->rules('max:120'). The value is in $entry->attributes in mutating() and mutated(), and in the Changes of the update policy on update, sync and toggle. The draft of a create check does not hold it. The field is never selected, sorted, filtered, searched, aggregated or returned, and /details and the OpenAPI document show it as a write-only field. It replaces virtual()->writeOnly()->fillUsing(fn () => null). See Input-only fields.
  • An input-only field with fillUsing(), resolveUsing(), filterUsing(), sortUsing(), searchable(), filterable(), sortable() or selectable(), in any order, or in pivotFields(), throws InvalidFieldException. filterable(false), sortable(false) and selectable(false) are accepted.
  • persistedBy() declares a pivot persister on a many-to-many relation: BelongsToMany::make('members', MemberResource::class)->persistedBy(ProjectMemberships::class). The class implements Lomkit\Rest\Contracts\PivotPersister, and its attach(), detach() and updatePivot() each receive a Lomkit\Rest\Mutations\PivotWrite. Validation, the policy and link checks, the transaction and its retries stay with the package. Without persistedBy(), Lomkit\Rest\Mutations\EloquentPivots writes the pivot table. See Pivot persisters.
  • After attach() and detach() of a declared persister, the package reads the links through the Eloquent relation, and throws Lomkit\Rest\Exceptions\PivotPersisterException when a row is not linked, or still linked. A persister that keeps withdrawn rows declares the condition on the Eloquent relation, such as ->wherePivotNull('withdrawn_at'). See Persisters that keep pivot rows.

Changes in 3.1.1

Version 3.1.1 fixes bugs and adds no feature. Upgrade with composer update lomkit/laravel-rest-api. One answer changes:

  • Sync limit. A sync detaches at most rest.limits.totals.entries rows, 1000 by default. A sync that would detach more was accepted before, and now answers a 422 on the key of the entry and writes nothing: The mutate.0.relations.tags.0.key field leaves out more than 1000 attached rows, the most that a sync detaches. To empty a large relation, send detach entries, or raise the limit in config/rest.php. See Attached rows.
  • Reads. toggle and a sync with "without_detaching": true read only the attached rows that their keys name, instead of every attached row of the parent.

Upgrading to 3.1 from 3.0

Version 3.1 adds features: a relation can choose the mutation operations that it accepts. Upgrade with composer update lomkit/laravel-rest-api, then go through the checks below.

Check after upgrading

  • rest:check is stricter. It now fails for each relation that accepts detach while its foreign key or morph type does not accept null. A resource generated with 3.0 on a NOT NULL foreign key sees rest:check exit with 1 until the relation withdraws detach or the column becomes nullable:
    BelongsTo::make('team', TeamResource::class)->withoutOperations(MutationOperation::Detach),
    

    See Relations that detach.
  • MySQL without strict mode. A detach on a NOT NULL foreign key used to write 0 or '' there. It now answers a 422 on the key of the entry, as on every database: The mutate.0.relations.team.key field is prohibited: this relation cannot be detached, its link column does not accept null.

What 3.1 adds

  • withoutOperations() withdraws operations from a relation, onlyOperations() keeps only some, and onlyOperations() without arguments makes it read-only. Validation, the details and the OpenAPI document follow. See Limiting the operations.
  • A many-to-many relation without detach accepts no toggle, and its sync needs "without_detaching": true. A relation without update writes its related rows on create only, and still writes the pivot.
  • A detach that would set a link column that does not accept null answers a 422, instead of a database error. Under a HasOne or MorphOne that cannot detach its row, the already holds a record message says what the relation accepts instead. See Writing relations.
  • rest:resource --generate and rest:quick-start add ->withoutOperations(MutationOperation::Detach) to the relations whose link column does not accept null. See Generating the fields and relations.
  • rest:check reports the relations above, reads the database schema for it, and adds relations to its --json report.
  • The OpenAPI document lists the 409 of a versioned resource on every operation that takes relations.

Changes in 3.0.1

Version 3.0.1 fixes bugs and adds no feature. Upgrade with composer update lomkit/laravel-rest-api. Some answers change:

  • Values. A Boolean or DateTime field on a column without cast now returns true or false, and the date through serializeDate() of the model, 2026-02-10T09:30:00.000000Z by default, instead of 1 and the stored text. See Value types in rows.
  • Requests that now answer 422: two includes without alias that load the same relation (only the last one was kept), see Aliases; an attach of a row that is already attached; nested relation lists over totals.entries once counted for each row of their parent, see Mutate limits; the relations of an attach, detach, sync or toggle entry that break a prohibitedOnUpdate() or requiredOnUpdate() constraint; input that is not valid UTF-8, see UTF-8 input.
  • Policies. An update policy now also sees the foreign key of a row moved to a row that the request creates, with a null value: read $changes->target('team_id') for the target row. A sync entry with pivot checks the link of the rows that it keeps attached. See Row checks.
  • Actions. An action with authorizeEach() runs on the rows that passed its checks only, and the checks stop at $maxResources. See Checking each row.
  • Metrics. A cached metric result keys the perimeters and the authorizationCacheContext() of every resource that its search reaches: the results kept before the upgrade are computed again once. See Caching a result.
  • Text search. On MySQL and MariaDB, a websearch text made of excluded words only returns the rows without these words, as on PostgreSQL.
  • Configuration. An empty REST_AUTHORIZATIONS_CACHE_STORE= uses the default cache store. In a published config/rest.php, change the line to 'store' => env('REST_AUTHORIZATIONS_CACHE_STORE') ?: null,.
  • Generators. rest:resource --generate checks a unique column on update too, and makes the encrypted columns neither filterable nor sortable. Check the resources generated with 3.0.0.

Upgrading to 3.0 from 2.x

Version 3.0 types every declaration, validates every payload against these types, and reads each request through one perimeter and one set of policy checks. Most applications change their resources more than their clients: fields become objects, the request argument of the declarations goes away, and the query hooks become one perimeterQuery().

This page summarizes the changes by area and links to the page that documents each one. The package's UPGRADE.md lists every change, with the exact messages and the edge cases: read it before you deploy.

PHP stops on a class whose override keeps an old signature, and names the method. Run your test suite and php artisan route:list after each step: most of the upgrade is driven by these errors.

Requirements

  • PHP 8.3 or higher, and Laravel 13.30 or higher. Applications on Laravel 12 stay on 2.x.
  • Laravel Scout 11.9 or higher, when Scout is installed.
  • Scramble ^0.13.48 for the OpenAPI document.

See Installation.

Configuration

Compare your published config/rest.php with the package file, then:

  • Remove authorizations.enabled and gates.enabled. Override isAuthorizingEnabled() or isGatingEnabled() on your base resource and return false instead.
  • Remove authorizations.cache.default. Each resource declares the seconds of each ability in authorizationCache().
  • Remove gates.message.enabled: each gate answer now holds allowed and message.
  • Move search.max_nesting_depth to limits.depths.filters.
  • Remove the documentation block.
  • New keys: authorizations.strict, authorizations.cache.store, morph.type_key, search.select_columns, search.more_key, transactions.attempts and the limits block. Copy the limits block of the package file: it bounds the lists, depths, totals and values of a request, the rows of a response (sizes.rows), the jobs of a queued action (sizes.jobs) and the groups of a metric (sizes.groups).
  • The defaults now merge into your file at every level, and each value is type-checked: a wrong type throws an exception that names the key.

See Configuration.

Routing

  • Rest::resource() takes two arguments. Replace the $options array with only(), except(), names(), middleware() and withSoftDeletes(). A forgotten third argument is ignored.
  • The resource name is one URI segment. Wrap the call in Route::prefix('admin') instead of admin/users.
  • middleware() adds to the package middleware instead of replacing it.
  • Each action and each metric has its own route, named {name}.operate.{uriKey} and {name}.metric.{uriKey}. actions() and metrics() are read when the routes register: return the same list for every user, and run php artisan route:cache again after a change.
  • The force delete endpoint is named forceDestroy: route name {name}.forceDestroy, controller method forceDestroy(). The URI stays {name}/force.
  • withSoftDeletes() throws when the model does not use SoftDeletes.

See Resources.

Resources and controllers

  • $model and $resource are typed: public static string $model = Post::class;.
  • The declarations take no argument: fields(), relations(), scopes(), limits(), actions(), instructions(), rules(), createRules(), updateRules(), defaultOrderBy() and the others. Read the request with $this->request().
  • The declarations are evaluated once per request. Read them with $resource->definition(): getFields(), getRelations() and the other getters are removed.
  • The controller hooks are removed. Move their code to the endpoint events of the resource, such as searching() and mutatedAll(). See Events and hooks.
  • Controller no longer extends Laravel's controller: declare middleware with HasMiddleware or the #[Middleware] attribute.

See Resources.

Fields

  • fields() returns typed field objects instead of column names: ID, Text, Integer, Number, Boolean, Date, DateTime, Enum and Json. Add ->nullable() to nullable columns.
  • A field decides how it is selected, sorted, filtered and written: readonly(), writeOnly(), virtual(), selectable(), sortable(), filterable(), creatable(), updatable(), resolveUsing(), fillUsing().
  • The ID field and readonly() fields are refused in attributes. Declare ->creatable() on a key that clients send.
  • A search loads only the columns its rows need. A policy or a custom response that reads another column needs it in alwaysSelect(), or in the requires() of a field.
  • The appended attributes of a model are no longer returned. Use a virtual() field with resolveUsing().
  • A row returns each value in the type of its field: a Number or Integer field turns a numeric string, such as the value of a decimal:2 cast, into a number ("25000.50" becomes 25000.5), and a Json field returns an empty array as {}. Read these values as numbers and objects in your clients.
  • A field type of your application that already defines a method named render() renames it, or gives it the signature render(mixed $value): mixed.
  • Enum::make('status')->offered([...]) withdraws some cases from writes, and keeps them readable and filterable.

See Fields.

Scopes, instructions and actions inputs

  • scopes() returns Scope objects, and their parameters are typed fields, bound by position.
  • The fields() of instructions and actions return typed fields instead of rule maps.
  • handle() receives an ActionFields or InstructionFields object instead of an array: $fields->plan instead of $fields['plan'].

See Scopes and instructions and Actions.

Relations

  • withPivotFields() and withPivotRules() are replaced by pivotFields([...]) with typed fields.
  • MorphTo declares its targets: MorphTo::make('labelable', [BookResource::class, ShelfResource::class]). Each row of a MorphTo include starts with its @type.
  • The callbacks of requiredOnCreation() and the other constraints receive the request and the related resource.
  • sync and toggle are accepted on many-to-many relations only. Through relations take no entry.
  • Child relations can delete rows in a mutation once they declare deletable(). See Deleting child rows.

See Relationships.

Validation

  • Every payload is validated in one pass, with rules on explicit keys such as search.filters.0.field and mutate.0.attributes.name.
  • A key that the package does not know inside an object of a payload gives a 422: The search.filters.0.operater field is prohibited. Unknown keys at the first level stay ignored.
  • The field rules apply to mutations: null is refused unless the field is nullable().
  • Fields take label() and messages().
  • Every list, depth and total is limited by rest.limits.
  • A string filter value, and each string of a list, takes at most rest.limits.lengths.values characters, 1,000 by default, whatever its operator. Before, a value of = or in had no length limit.
  • A search takes at most rest.limits.totals.patterns pattern filters (like, not like, ilike, not ilike), 10 by default.
  • A search page, or the response block of a mutation, renders at most rest.limits.sizes.rows rows, 10,000 by default, counted from the page limit and the include limits before any query. A search over it gets a 422: ask for smaller limits, or raise the limit.
  • Keys are typed by the ID field, and checked through perimeterQuery().
  • The messages that the package writes itself are translation lines under the rest namespace, shipped in English and French. A JSON translation line keyed by an English sentence of the package no longer applies: publish the files with php artisan vendor:publish --tag=rest-lang and edit them in lang/vendor/rest. See Translations.

See Validation and Limits.

Perimeter

  • searchQuery() is renamed perimeterQuery() and applies to every endpoint, at every level of a request.
  • mutateQuery(), destroyQuery(), restoreQuery() and forceDeleteQuery() are removed. Move their conditions to a policy or to perimeterQuery().
  • perimeterQuery() takes the builder only and declares its return type.
  • php artisan rest:check fails for a resource that the routes reach without its own perimeterQuery(). Override it, or mark the resource #[WithoutPerimeter] when every row is meant for every user who passes viewAny.
  • The KeysOutOfReach event tells a listener when a request names keys outside the perimeter.

See Perimeter.

Authorization

  • Each request checks viewAny on its endpoint and on every resource its payload reaches before validation: a 403 now comes before a 422.
  • Each created row is checked with its draft, and each updated row with its Changes.
  • The links of a relation are checked with the abilities it declares, ->abilities(attach: 'attachTag', detach: 'detachTag'), or with update on the parent.
  • The decision cache keeps only the abilities a resource declares in authorizationCache().
  • restore and forceDelete are gates, and restore and forceDestroy are abilities in the details, only when the model uses SoftDeletes. Remove them from the gates of a search on another resource, where they give a 422.
  • authorizations.strict reports a check that the request did not plan.

See Policies, Gates and Decision cache.

  • An include returns at most its limit rows per parent, or the $includeLimit of its resource, 10 by default. @more tells which lists are cut.
  • = and != with null give a 422: use is null and is not null on a nullable field.
  • The operators depend on the type of the field. ilike, between, is null and relation groups are new.
  • Every order ends with the model key.
  • A sort on the key of an aggregate needs an aggregate over a relation to many, with no field or on a field that is not a key. author_count on a BelongsTo relation, or comments_max_id, gives a 422. See Sort on an aggregate.
  • A text search is declared with text(): Contains, FullText or ScoutEngine. A Scout model no longer gives its resource a text search by itself.
  • searchMeta() on a resource adds keys to the meta of a search page, see Meta. On an instruction, it adds an object under meta.instructions, see Instruction meta.
  • Rest::search() runs a search outside HTTP, and lazy() reads every row of it for an export. See Searching outside HTTP.

See Search, Filters, Text search, Search engines and Searching outside HTTP.

Writes

  • The mutate endpoint answers operations instead of created and updated, and returns the written rows with a response block.
  • Versioned rows are new: the update entries of a versioned() resource accept the version that the client read, and the mutation answers 409 and writes nothing when the row changed since. See Versioned rows.
  • Writes run in one transaction on the connection of the model, and can run again on a deadlock.
  • The keys that a parent relation sets win over the attributes of the entry.
  • The package writes every mutation, not a query builder or a relation class: beforeMutating(), afterMutating() and the write methods of the relations are no longer called. To change what a write does, use 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 on the relation with persistedBy(), from 3.2. See Pivot persisters.
  • destroy, restore and forceDestroy check every row before they write any, and write them in one transaction.
  • An entry that only links a row (attach, detach, sync, toggle without attributes) is not saved and runs no mutating() or mutated() hook, unless its own relations change: then the hooks of its resource run for that row.
  • A resource can ask for a confirmation before mutate, destroy, restore or forceDestroy writes, with mutateConfirmation(), destroyConfirmation(), restoreConfirmation() and forceDestroyConfirmation(): the endpoint answers 428 and writes nothing until the client sends the token back. A resource that already defines one of these methods, confirms() or confirmations() renames it. See Confirmation.

See Mutate, Writing relations, Versioned rows and Deleting.

Responses

  • meta and pivot are objects, {} when empty.
  • Each gate answer is {"allowed": ..., "message": ...}.
  • A row returns the relations that its search includes, and no other.
  • A custom Response keeps map() only.
  • Each value follows the type of its field: Number and Integer values are numbers, an empty Json value is {}. See Value types in rows.

See Responses.

Details

  • The details endpoint answers a thin base: fields with their name, label, type and nullable, limits and meta. Ask for the rest with the with query parameter, such as GET /api/products?with=fields.capabilities,relations.operations,authorizations. What is not asked for is not computed. See Asking for more with with.
  • The entries are typed: fields with their capabilities and rules, relations with their operations, inputs, text search, gates and authorizations.
  • actions.authorized and metrics.authorized tell whether the user may run each action and metric.
  • An Enum entry adds offered next to values when offered() leaves cases out, and with=confirmations tells which writes ask for a confirmation.

See Details.

Actions, events and metrics

  • Actions choose their rows with ActionTarget instead of standalone() and targeted(), and can answer with a result, ask for a confirmation with a 428 answer and check each row.
  • An action with the Search target requires search. Send "search": {} to run it on every row of the perimeter: a body without search answers 422, The search field is required. Before, it ran the action on every row. Add "search": {} to each client call that runs such an action without a search.
  • Queued actions run in the worker as the user who sent the request. One run creates at most rest.limits.sizes.jobs jobs, 100 by default: past that, each job takes more rows than $chunkCount.
  • ActionTransaction::Row runs each row in its own transaction, through handleRow(), with beforeRow() outside it for a call to another service. An action that already defines beforeRow(), handleRow() or transactionPerRow() gives them this signature and this meaning.
  • The controller hooks are replaced by resource events, and writes dispatch Laravel events.
  • Metrics are new. A partition keeps its 100 largest parts and a split trend its 100 largest splits unless the metric sets limit(): see rest.limits.sizes.groups.

See Actions, Queued actions, Confirmation, Metrics and Events and hooks.

OpenAPI

  • The built-in documentation generator is removed, with the /api-documentation route, rest:documentation and Rest::withDocumentationCallback().
  • Install Scramble: the package registers its documentation itself, and documents every endpoint from the declarations.
  • The request examples honour the simple rules of each field and never send a default. A key that an endpoint refuses is documented as "<key>": false. Declare examples() on a field whose rules the example does not pass.

See OpenAPI.

Generators

  • The generated classes are typed and pass Larastan at level 10. Delete or republish the stubs that you published under 2.x: their untyped properties are a fatal error in 3.0.
  • rest:resource --generate declares the fields and relations from the table of the model. It leaves out the columns that the authentication flow writes, such as remember_token, and names the real targets of a skipped MorphTo relation.
  • rest:policy and rest:metric are new, and rest:quick-start asks which models to expose.

See Resources and Artisan.

Removed features

RemovedReplacement
authorizations.enabled, gates.enabledisAuthorizingEnabled(), isGatingEnabled()
DisableAuthorizations, DisableGates, DisableAuthorizationsCache traitsthe methods above, authorizationCache()
searchQuery()perimeterQuery()
mutateQuery(), destroyQuery(), restoreQuery(), forceDeleteQuery()perimeterQuery() or a policy
controller hooks (beforeSearch(), afterMutate(), ...)resource events
withPivotFields(), withPivotRules()pivotFields()
standalone(), targeted()ActionTarget
scoutFields(), scoutInstructions(), searchScoutQuery()ScoutEngine::make() in text()
Lomkit\Rest\Query\Builder and its bindingperimeterQuery(), model scopes, searching()
built-in OpenAPI generator, /api-documentationScramble
lomkit-rest container aliasLomkit\Rest\Rest or the Rest facade

Steps

  1. Update PHP and Laravel, then run composer require lomkit/laravel-rest-api:^3.0.
  2. Update config/rest.php.
  3. Type $model and $resource, remove the request parameter of every declaration, and replace the field names with field objects.
  4. Rename searchQuery() to perimeterQuery() and move the other query hooks.
  5. Move the controller hooks to the resource events.
  6. Update the actions, the instructions and the scopes.
  7. Run the queued actions of 2.x before you deploy: a job queued before the upgrade cannot run after it.
  8. Update the clients: the operations response of mutate, the gate answers, is null filters, include limits, the MorphTo declarations, numbers where decimal columns returned strings, and "search": {} on the actions that run on every row.