Upgrade guide
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 runphp artisan rest:check. See Instructions. rest:check. Thedeclarationssection counts the instructions that it builds,4 actions, 2 metrics, 3 instructions built, and thedeclarationskey ofrest:check --jsongainsinstructions: 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 withoutinstructions, 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 andrest:checkbuild their own. - Instructions have no route, so an instruction listed by its class can still override
name()oruriKey(). - When the instructions are read,
InvalidInstructionExceptionrefuses a name that is not a class extendingInstruction,Instruction::classitself, an abstract class, and a container binding that returns another class, with a message that names the resource. See Declaration checks. rest:checkbuilds 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 itsdeclarationssection, 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:instructionprints 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 itsuriKeyproperty. See Caching a result. - Cached routes. After you change the key or the middleware of an action or a metric, run
php artisan route:cacheagain. Until then, the action or the metric throwsInvalidActionExceptionorInvalidMetricExceptionand 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 runphp artisan rest:check. The report adds adeclarationssection, andrest:check --jsonadeclarationskey: a script that reads the report key by key sees it. See Checking the application.
What 3.4 adds
actions()andmetrics()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,$targetor$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
$uriKeyproperty, which sets the route key apart from the name:public ?string $uriKey = 'end';onEndAttachmentActiongives/actions/end, and/detailskeeps the nameEnd Attachment. See Route key and name. - When the routes register,
InvalidActionExceptionorInvalidMetricExceptionrefuses a class that overridesname()oruriKey(), an abstract class,Action::classorMetric::classitself, and a class of the other kind. The other declaration errors of a class throw when it is first built, andrest:checkbuilds 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
ActionFieldsandInstructionFieldstakerequired: true:$fields->date('last_day', required: true)is aCarbonImmutablefor PHPStan, not a?CarbonImmutable. Anullvalue throwsInvalidFieldException: give the input therequiredrule. See Required reads. rest:actionandrest:metricprint 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\WithCachedRoutestrait on the base test case keeps the routes of the first test for the following tests, soRest::resource()no longer runs between tests. With the trait, a route registered after the application booted is matched by URL, butroute('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
conflictsof a409has areason:versionon a version conflict, which keeps itspath,keyandversion, andunlistedon a has-many sync. A client that compares a conflict item key by key sees the new key. See Conflicts. - Details.
/detailsaddssyncto each relation, withrelations.operations:replace,linkorcheck, andnullwhen the relation takes nosync. See Relations. - Relation classes of your application. A relation subclass that already declares
syncable(),isSyncable()orsyncsChildren()renames its method. A custom relation that listsMutationOperation::SyncinmutationOperations()keeps its sync, which links the rows that it names and checks nothing.
What 3.3 adds
ActionFieldsandInstructionFieldsread an input in a given type:string(),integer(),float(),boolean(),date(),enum()andarray(), such as$fields->enum('status', Status::class). Each returns the value that the field cast, ornull.float()also converts anintor a numeric string, andinteger()a string that is exactly an integer. A value of another type throwsInvalidFieldException.$fields->reasonkeeps working. See Typed readers.PivotWrite::user()returns the user that the package checked the policies for,nullfor a guest, so a pivot persister can record who linked a row without reading the authentication state. See The persister contract.ActionandInstructiondeclare their model as a PHPStan template with a default,@template TModel of Model = Model./** @extends Action<Invoice> */narrowshandle(),beforeRow()andhandleRow(), and/** @extends Instruction<Invoice> */the query ofhandle(). A class without@extendsgets no new error at any level. See The model of an action.- A
HasManyorMorphManyrelation acceptssyncwithsyncable(). Thesynclists the children to keep and writes nothing; thecreate,update,deleteanddetachentries next to it write the changes. Before any write, the package checks that they account for every child that the user can see, and answers409otherwise: 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
conflictsitems as aoneOfof the two shapes, and lists the409on a mutation that reaches asyncable()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.neonthat lets PHPStan read the inputs ofActionFieldsandInstructionFieldsas properties, such as$fields->reason.phpstan/extension-installerincludes it. Without it, addvendor/lomkit/laravel-rest-api/extension.neonto theincludesof yourphpstan.neon. See Static analysis. new static(). A subclass that redefinesmake()withnew 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, andactions()andmetrics()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 withapp(X::class), or, since 3.4, list it by its class.instructions()is read when a search or/detailsfirst 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 withsortsor alimit, no longer fails when an instruction, a scope, or aMorphToor aliased include decorates the rows with anafterQuery()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 typedIlluminate\Database\Eloquent\Collectionthrew aTypeErrorand the request answered500. - 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
DateTimevalue with an offset, such as2026-10-12T08:00:00+02:00, is converted toconfig('app.timezone')before it reaches the database: in filters, with every operator,betweenandnot betweenincluded, inmutateattributes and pivot fields, and in the inputs of scopes, instructions and actions. Before, the offset was dropped: withUTC, a filter compared08:00:00and missed the row stored at06:00:00, and a write stored08: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 aDateTimesubclass. - What stays the same. A value without an offset is read in the application timezone. A
Datevalue keeps the day as sent.fillUsing()andfilterUsing()callbacks, and$entry->attributesinmutating()andmutated(), 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
updateentries under a many-to-many relation read whether the rows they name are attached, through theperimeterQuery()of the related resource, astoggledoes. See Attached rows.togglekeeps a hidden row attached. Atoggleleaves 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
syncortogglewrites its deletes, then its inserts, then its pivot updates. See Order of the pivot writes. - Touches. A
togglethat both detaches and attaches rows, and asyncthat both attaches rows and updates the pivot of others, touch the models of$touchestwice 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 columnreadonly(),creatable(false)orupdatable(false), or leave it out offields(). See Columns that a hook fills.
What 3.2 adds
inputOnly()declares a field thatmutatevalidates and hands to the hooks without writing it on the model:Text::make('delivery_address')->inputOnly()->rules('max:120'). The value is in$entry->attributesinmutating()andmutated(), and in theChangesof theupdatepolicy onupdate,syncandtoggle. The draft of acreatecheck does not hold it. The field is never selected, sorted, filtered, searched, aggregated or returned, and/detailsand the OpenAPI document show it as a write-only field. It replacesvirtual()->writeOnly()->fillUsing(fn () => null). See Input-only fields.- An input-only field with
fillUsing(),resolveUsing(),filterUsing(),sortUsing(),searchable(),filterable(),sortable()orselectable(), in any order, or inpivotFields(), throwsInvalidFieldException.filterable(false),sortable(false)andselectable(false)are accepted. persistedBy()declares a pivot persister on a many-to-many relation:BelongsToMany::make('members', MemberResource::class)->persistedBy(ProjectMemberships::class). The class implementsLomkit\Rest\Contracts\PivotPersister, and itsattach(),detach()andupdatePivot()each receive aLomkit\Rest\Mutations\PivotWrite. Validation, the policy and link checks, the transaction and its retries stay with the package. WithoutpersistedBy(),Lomkit\Rest\Mutations\EloquentPivotswrites the pivot table. See Pivot persisters.- After
attach()anddetach()of a declared persister, the package reads the links through the Eloquent relation, and throwsLomkit\Rest\Exceptions\PivotPersisterExceptionwhen 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
syncdetaches at mostrest.limits.totals.entriesrows, 1000 by default. Asyncthat would detach more was accepted before, and now answers a422on thekeyof 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, senddetachentries, or raise the limit inconfig/rest.php. See Attached rows. - Reads.
toggleand asyncwith"without_detaching": trueread 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:checkis stricter. It now fails for each relation that acceptsdetachwhile its foreign key or morph type does not accept null. A resource generated with 3.0 on aNOT NULLforeign key seesrest:checkexit with1until the relation withdrawsdetachor the column becomes nullable:BelongsTo::make('team', TeamResource::class)->withoutOperations(MutationOperation::Detach),
See Relations that detach.- MySQL without strict mode. A
detachon aNOT NULLforeign key used to write0or''there. It now answers a422on thekeyof 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, andonlyOperations()without arguments makes it read-only. Validation, the details and the OpenAPI document follow. See Limiting the operations.- A many-to-many relation without
detachaccepts notoggle, and itssyncneeds"without_detaching": true. A relation withoutupdatewrites its related rows oncreateonly, and still writes the pivot. - A
detachthat would set a link column that does not accept null answers a422, instead of a database error. Under aHasOneorMorphOnethat cannot detach its row, thealready holds a recordmessage says what the relation accepts instead. See Writing relations. rest:resource --generateandrest:quick-startadd->withoutOperations(MutationOperation::Detach)to the relations whose link column does not accept null. See Generating the fields and relations.rest:checkreports the relations above, reads the database schema for it, and addsrelationsto its--jsonreport.- The OpenAPI document lists the
409of a versioned resource on every operation that takesrelations.
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
BooleanorDateTimefield on a column without cast now returnstrueorfalse, and the date throughserializeDate()of the model,2026-02-10T09:30:00.000000Zby default, instead of1and 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; anattachof a row that is already attached; nested relation lists overtotals.entriesonce counted for each row of their parent, see Mutate limits; therelationsof anattach,detach,syncortoggleentry that break aprohibitedOnUpdate()orrequiredOnUpdate()constraint; input that is not valid UTF-8, see UTF-8 input. - Policies. An
updatepolicy now also sees the foreign key of a row moved to a row that the request creates, with anullvalue: read$changes->target('team_id')for the target row. Asyncentry withpivotchecks 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
websearchtext 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 publishedconfig/rest.php, change the line to'store' => env('REST_AUTHORIZATIONS_CACHE_STORE') ?: null,. - Generators.
rest:resource --generatechecks a unique column on update too, and makes theencryptedcolumns 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 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.48for the OpenAPI document.
See Installation.
Configuration
Compare your published config/rest.php with the package file, then:
- Remove
authorizations.enabledandgates.enabled. OverrideisAuthorizingEnabled()orisGatingEnabled()on your base resource and returnfalseinstead. - Remove
authorizations.cache.default. Each resource declares the seconds of each ability inauthorizationCache(). - Remove
gates.message.enabled: each gate answer now holdsallowedandmessage. - Move
search.max_nesting_depthtolimits.depths.filters. - Remove the
documentationblock. - New keys:
authorizations.strict,authorizations.cache.store,morph.type_key,search.select_columns,search.more_key,transactions.attemptsand thelimitsblock. Copy thelimitsblock 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$optionsarray withonly(),except(),names(),middleware()andwithSoftDeletes(). A forgotten third argument is ignored.- The resource name is one URI segment. Wrap the call in
Route::prefix('admin')instead ofadmin/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()andmetrics()are read when the routes register: return the same list for every user, and runphp artisan route:cacheagain after a change. - The force delete endpoint is named
forceDestroy: route name{name}.forceDestroy, controller methodforceDestroy(). The URI stays{name}/force. withSoftDeletes()throws when the model does not useSoftDeletes.
See Resources.
Resources and controllers
$modeland$resourceare 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()andmutatedAll(). See Events and hooks. Controllerno longer extends Laravel's controller: declare middleware withHasMiddlewareor the#[Middleware]attribute.
See Resources.
Fields
fields()returns typed field objects instead of column names:ID,Text,Integer,Number,Boolean,Date,DateTime,EnumandJson. 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
IDfield andreadonly()fields are refused inattributes. 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 therequires()of a field. - The appended attributes of a model are no longer returned. Use a
virtual()field withresolveUsing(). - A row returns each value in the type of its field: a
NumberorIntegerfield turns a numeric string, such as the value of adecimal:2cast, into a number ("25000.50"becomes25000.5), and aJsonfield 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 signaturerender(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()returnsScopeobjects, and their parameters are typed fields, bound by position.- The
fields()of instructions and actions return typed fields instead of rule maps. handle()receives anActionFieldsorInstructionFieldsobject instead of an array:$fields->planinstead of$fields['plan'].
See Scopes and instructions and Actions.
Relations
withPivotFields()andwithPivotRules()are replaced bypivotFields([...])with typed fields.MorphTodeclares its targets:MorphTo::make('labelable', [BookResource::class, ShelfResource::class]). Each row of aMorphToinclude starts with its@type.- The callbacks of
requiredOnCreation()and the other constraints receive the request and the related resource. syncandtoggleare 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.fieldandmutate.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:
nullis refused unless the field isnullable(). - Fields take
label()andmessages(). - 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.valuescharacters, 1,000 by default, whatever its operator. Before, a value of=orinhad no length limit. - A search takes at most
rest.limits.totals.patternspattern filters (like,not like,ilike,not ilike), 10 by default. - A search page, or the
responseblock of a mutation, renders at mostrest.limits.sizes.rowsrows, 10,000 by default, counted from the page limit and the include limits before any query. A search over it gets a422: ask for smaller limits, or raise the limit. - Keys are typed by the
IDfield, and checked throughperimeterQuery(). - The messages that the package writes itself are translation lines under the
restnamespace, shipped in English and French. A JSON translation line keyed by an English sentence of the package no longer applies: publish the files withphp artisan vendor:publish --tag=rest-langand edit them inlang/vendor/rest. See Translations.
See Validation and Limits.
Perimeter
searchQuery()is renamedperimeterQuery()and applies to every endpoint, at every level of a request.mutateQuery(),destroyQuery(),restoreQuery()andforceDeleteQuery()are removed. Move their conditions to a policy or toperimeterQuery().perimeterQuery()takes the builder only and declares its return type.php artisan rest:checkfails for a resource that the routes reach without its ownperimeterQuery(). Override it, or mark the resource#[WithoutPerimeter]when every row is meant for every user who passesviewAny.- The
KeysOutOfReachevent tells a listener when a request names keys outside the perimeter.
See Perimeter.
Authorization
- Each request checks
viewAnyon its endpoint and on every resource its payload reaches before validation: a403now comes before a422. - 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 withupdateon the parent. - The decision cache keeps only the abilities a resource declares in
authorizationCache(). restoreandforceDeleteare gates, andrestoreandforceDestroyare abilities in the details, only when the model usesSoftDeletes. Remove them from thegatesof a search on another resource, where they give a422.authorizations.strictreports a check that the request did not plan.
See Policies, Gates and Decision cache.
Search
- An include returns at most its
limitrows per parent, or the$includeLimitof its resource, 10 by default.@moretells which lists are cut. =and!=withnullgive a422: useis nullandis not nullon a nullable field.- The operators depend on the type of the field.
ilike,between,is nulland 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_counton aBelongsTorelation, orcomments_max_id, gives a422. See Sort on an aggregate. - A text search is declared with
text():Contains,FullTextorScoutEngine. A Scout model no longer gives its resource a text search by itself. searchMeta()on a resource adds keys to themetaof a search page, see Meta. On an instruction, it adds an object undermeta.instructions, see Instruction meta.Rest::search()runs a search outside HTTP, andlazy()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
operationsinstead ofcreatedandupdated, and returns the written rows with aresponseblock. - Versioned rows are new: the
updateentries of aversioned()resource accept theversionthat the client read, and the mutation answers409and 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 themutating()andmutated()hooks of the resource. The pivot rows of a many-to-many relation are written beforemutated()runs: to write them another way, declare a pivot persister on the relation withpersistedBy(), from 3.2. See Pivot persisters. destroy,restoreandforceDestroycheck every row before they write any, and write them in one transaction.- An entry that only links a row (
attach,detach,sync,togglewithout attributes) is not saved and runs nomutating()ormutated()hook, unless its ownrelationschange: then the hooks of its resource run for that row. - A resource can ask for a confirmation before
mutate,destroy,restoreorforceDestroywrites, withmutateConfirmation(),destroyConfirmation(),restoreConfirmation()andforceDestroyConfirmation(): the endpoint answers428and writes nothing until the client sends the token back. A resource that already defines one of these methods,confirms()orconfirmations()renames it. See Confirmation.
See Mutate, Writing relations, Versioned rows and Deleting.
Responses
metaandpivotare objects,{}when empty.- Each gate answer is
{"allowed": ..., "message": ...}. - A row returns the relations that its search includes, and no other.
- A custom
Responsekeepsmap()only. - Each value follows the type of its field:
NumberandIntegervalues are numbers, an emptyJsonvalue is{}. See Value types in rows.
See Responses.
Details
- The details endpoint answers a thin base:
fieldswith theirname,label,typeandnullable,limitsandmeta. Ask for the rest with thewithquery parameter, such asGET /api/products?with=fields.capabilities,relations.operations,authorizations. What is not asked for is not computed. See Asking for more withwith. - The entries are typed: fields with their capabilities and rules, relations with their operations, inputs, text search, gates and authorizations.
actions.authorizedandmetrics.authorizedtell whether the user may run each action and metric.- An
Enumentry addsofferednext tovalueswhenoffered()leaves cases out, andwith=confirmationstells which writes ask for a confirmation.
See Details.
Actions, events and metrics
- Actions choose their rows with
ActionTargetinstead ofstandalone()andtargeted(), and can answer with a result, ask for a confirmation with a428answer and check each row. - An action with the
Searchtarget requiressearch. Send"search": {}to run it on every row of the perimeter: a body withoutsearchanswers422,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.jobsjobs, 100 by default: past that, each job takes more rows than$chunkCount. ActionTransaction::Rowruns each row in its own transaction, throughhandleRow(), withbeforeRow()outside it for a call to another service. An action that already definesbeforeRow(),handleRow()ortransactionPerRow()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(): seerest.limits.sizes.groups.
See Actions, Queued actions, Confirmation, Metrics and Events and hooks.
OpenAPI
- The built-in documentation generator is removed, with the
/api-documentationroute,rest:documentationandRest::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. Declareexamples()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 --generatedeclares the fields and relations from the table of the model. It leaves out the columns that the authentication flow writes, such asremember_token, and names the real targets of a skippedMorphTorelation.rest:policyandrest:metricare new, andrest:quick-startasks which models to expose.
Removed features
| Removed | Replacement |
|---|---|
authorizations.enabled, gates.enabled | isAuthorizingEnabled(), isGatingEnabled() |
DisableAuthorizations, DisableGates, DisableAuthorizationsCache traits | the 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 binding | perimeterQuery(), model scopes, searching() |
built-in OpenAPI generator, /api-documentation | Scramble |
lomkit-rest container alias | Lomkit\Rest\Rest or the Rest facade |
Steps
- Update PHP and Laravel, then run
composer require lomkit/laravel-rest-api:^3.0. - Update
config/rest.php. - Type
$modeland$resource, remove the request parameter of every declaration, and replace the field names with field objects. - Rename
searchQuery()toperimeterQuery()and move the other query hooks. - Move the controller hooks to the resource events.
- Update the actions, the instructions and the scopes.
- Run the queued actions of 2.x before you deploy: a job queued before the upgrade cannot run after it.
- Update the clients: the
operationsresponse ofmutate, the gate answers,is nullfilters, include limits, theMorphTodeclarations, numbers where decimal columns returned strings, and"search": {}on the actions that run on every row.