Actions
An action is a class that runs your code on rows of a resource: close tickets, send a notification, export orders. Each action gets its own route, validates typed inputs, checks the policies of the rows and answers with the number of rows it ran on and an optional result.
Defining an action
Generate an action with the rest:action Artisan command. The class is written in app/Rest/Actions:
php artisan rest:action ExtendSubscriptions
namespace App\Rest\Actions;
use Illuminate\Support\Collection;
use Lomkit\Rest\Actions\Action;
use Lomkit\Rest\Actions\ActionFields;
use Lomkit\Rest\Fields\Date;
use Lomkit\Rest\Fields\Enum;
class ExtendSubscriptions extends Action
{
public function fields(): array
{
return [
Date::make('expires_at')->rules('required'),
Enum::make('plan', Plan::class)->default(Plan::Monthly),
];
}
public function handle(ActionFields $fields, Collection $models): void
{
foreach ($models as $subscription) {
$subscription->update(['expires_at' => $fields->expires_at, 'plan' => $fields->plan]);
}
}
}
List it by its class in the actions() method of the resource:
use App\Rest\Actions\ExtendSubscriptions;
public function actions(): array
{
return [
ExtendSubscriptions::class,
];
}
- The action is named after its class, without an
Actionsuffix:ExtendSubscriptionsgives the nameExtend Subscriptionsand the keyextend-subscriptions. Set the$nameproperty to choose another name, and$uriKeyfor another key, see Route key and name. Rest::resource()readsactions()when it registers the routes, without a user. Keep the list the same for every user and free of queries, and runphp artisan route:cacheagain after you add an action.- Registering the routes builds no class: the package reads the key and the middleware of the action from the default values of its properties. The container builds the action only when it is used: an
operaterequest for its key,/details, the OpenAPI document,rest:checkor a queued run. A request for another action does not build it. - Inside an action,
$this->resourceis the resource and$this->request()the request of the endpoint.
rest:action prints the line to add: List it in the actions() of a resource by its class: ExtendSubscriptions::class.
Configuring an action
An action carries its own configuration in its properties:
use Lomkit\Rest\Actions\Action;
use Lomkit\Rest\Actions\ActionTarget;
class CloseTickets extends Action
{
public ?string $name = 'Close';
public ActionTarget $target = ActionTarget::Resources;
public array $middleware = ['throttle:tickets'];
public bool $destructive = true;
}
| Property | Sets | Page |
|---|---|---|
$name, $uriKey | the name in /details and the key of the route | Route key and name |
$target | the rows that the action runs on | Targets |
$maxResources | the most rows that one run reaches | Capping the rows |
$destructive, $confirm | the hints for clients | Hints for clients |
$skipUnauthorized | runs on the allowed rows only | Checking each row |
$chunkCount, $transaction | the size of the chunks and the transactions | Chunks and transactions |
$middleware, $withoutMiddleware | the middleware of the route | Middleware |
Set the key and the middleware as default values of the properties, not in the constructor: the package reads them without building the class, see Declaration checks.
Route key and name
$name is the label that /details gives to clients, and the route key derives from it. $uriKey sets the route key apart from the name:
class EndAttachmentAction extends Action
{
public ?string $uriKey = 'end';
}
The action gets POST /api/tickets/actions/end, named tickets.operate.end, and /details keeps the name End Attachment.
- Without
$uriKey, the key comes from$name:public ?string $name = 'End';gives the keyend. Without both, it comes from the class name:CloseTicketsgivesclose-tickets. $uriKeyworks on an instance too.- Two actions of one resource with one key throw
Lomkit\Rest\Exceptions\InvalidResourceRouteExceptionwhen the routes register.
Actions that inject services
The container builds an action listed by its class, so its constructor can inject services:
class InvoiceOrders extends Action
{
public function __construct(private readonly Billing $billing) {}
}
public function actions(): array
{
return [
InvoiceOrders::class,
];
}
- The constructor runs when the action is built, not when the routes register. A parameter that the container cannot resolve throws then:
rest:checkbuilds every action and reports it. rest:checkbuilds the action without a user. Resolve what depends on the user, such as the tenant, when the action runs, inhandle().- Metrics listed by their class are built the same way. Instructions listed by their class are built through the container too, when a search or
/detailsfirst reads the instructions of the resource, not when the routes register. See Instructions that inject services.
Reusing an action with other settings
List an instance when one action class serves several resources with other settings:
public function actions(): array
{
return [
ExportTickets::make()->middleware('throttle:exports')->meta(['color' => '#FFFFFF']),
];
}
->target(),->maxResources(),->destructive(),->confirm(),->skipUnauthorized(),->atomic(),->transactionPerRow(),->withoutTransaction(),->middleware()and->withoutMiddleware()set the properties of the table above on the instance.->meta(['color' => '#FFFFFF'])adds keys that the details give to clients with?with=actions.meta.getMeta()reads them. A class sets them with$this->meta([...])in its constructor.actions()creates the instances when the routes register, so their constructors run at boot, in every Artisan command and on every request while the routes are not cached.make()passes its arguments to the constructor, not through the container: inject nothing there that needs a user, a tenant, the database or keys.
Running an action
Each action gets the route POST /{resource}/actions/{uriKey}, named {name}.operate.{uriKey}:
POST /api/subscriptions/actions/extend-subscriptions
{
"fields": [{"name": "expires_at", "value": "2027-01-31"}],
"search": {"filters": [{"field": "status", "value": "active"}]}
}
{"data": {"impacted": 11, "result": null}}
fieldsis a list of{name, value}entries, not an object keyed by name. An object is a422:The fields field must be a list.Each name appears once, and an entry takesnameandvalueonly.impactedis the number of rows that the action ran on: the rows given tohandle(), or the rows put into the jobs of a queued action.- An unknown action answers
404to a user allowedviewAnyon the resource, and403to the others.
Targets
The target of an action sets the rows it runs on, and what the request may send. Set it with the $target property:
use Lomkit\Rest\Actions\ActionTarget;
class DeactivateUsers extends Action
{
public ActionTarget $target = ActionTarget::Resources;
}
An instance reused with other settings sets it with ->target(): SendDigest::make()->target(ActionTarget::None).
| Target | search | resources | Rows |
|---|---|---|---|
ActionTarget::Search, the default | required | refused | the rows that search matches inside the perimeter, every row with "search": {} |
ActionTarget::Resources | refused | required | the rows of the keys in resources, in their order |
ActionTarget::None | refused | refused | none: handle() receives an empty collection |
Search target, send "search": {} to run the action on every row of the perimeter. A body without search is a 422: The search field is required. Use ActionTarget::Resources when an action must never reach every row: the client then names each row by key.{"resources": [1, 5, 9], "fields": [{"name": "reason", "value": "spam"}]}
searchtakes the keys of a search, withoutpage, as an object.textworks on a resource that declares a text search.- A key of
resourcesthat does not exist, or thatperimeterQuery()leaves out, is a422underresources.{index}. A repeated key is a422too. A key outside the perimeter also dispatches theKeysOutOfReachevent. - The details, with
?with=actions, give the target of each action as"target": "search","resources"or"none".
Capping the rows
Every target is capped by the $maxResources property, 1000 by default. A search that matches more rows answers a 422 under search before the action runs on any row: This action can be run on at most 1000 resources; narrow the search.
public ?int $maxResources = 5000;
->maxResources(5000) sets it on an instance. null removes the cap: the action then runs on every row that its search matches, without counting them first.
Fields
fields() returns typed fields, the same classes as the fields of a resource. They take rules(), nullable(), default(), label() and messages().
- Each field is validated as a normal Laravel validation:
required,required_ifandpresentfire even when the field is absent fromfields. - An error is keyed by the field name,
fields.expires_at. An unknown or repeated name is reported by position,fields.0.name. - An
Enumfield names its enum class,Enum::make('plan', Plan::class), because action fields are not bound to a model. - The list takes at most
rest.limits.sizes.fieldsentries,100by default.
handle() receives a read-only Lomkit\Rest\Actions\ActionFields. Each declared input is a property cast to its field type, with its default filled in:
| Read | Gives |
|---|---|
$fields->expires_at | a CarbonImmutable for a Date, or for a DateTime in config('app.timezone'), the case for an Enum, null when not sent and without default |
$fields->has('reason') | true when the client sent it, null included, or when the field has a default |
$fields->filled('reason') | has() and not null, like isset($fields->reason) |
$fields->only('plan', 'reason'), $fields->toArray() | the inputs that has() reports, by name |
$fields->user() | the user who sent the request, also in a queued job |
$fields->target() | the ActionTarget of the action |
Reading an input that fields() does not declare throws Lomkit\Rest\Exceptions\InvalidFieldException.
Typed readers
A typed reader returns an input in one type, with the names of Laravel's Request:
$fields->string('reason'); // ?string
$fields->integer('quantity'); // ?int
$fields->float('rate'); // ?float
$fields->boolean('notify'); // ?bool
$fields->date('starts_on'); // ?CarbonImmutable
$fields->enum('status', Status::class); // ?Status
$fields->array('tags'); // ?array
- Each reader returns the value that the field cast, or
nullwhen the value isnull: sent asnull, or not sent and without default. date()reads aDatefield, and aDateTimefield inconfig('app.timezone').float()also converts anintor a numeric string: aNumbersent as"19.99"gives19.99.integer()converts a string that is exactly an integer:"3"gives3, while"3.5"and"1e3"throw. The other readers convert nothing.- A value of another type, a case of another enum included, throws
InvalidFieldException, as a name thatfields()does not declare does.$fields->integer('expires_at')in the action above gives:
The input [expires_at] of App\Rest\Actions\ExtendSubscriptions::fields() is [Carbon\CarbonImmutable], not [int].
- A property keeps the value as the field cast it:
$fields->priceon aNumbersent as"19.99"stays that string.has(),filled(),only()andtoArray()do not change.
Required reads
Every typed reader takes required: true. It then returns the non-null type, and PHPStan reads that type:
$fields->date('expires_at', required: true); // CarbonImmutable
$fields->date('expires_at'); // ?CarbonImmutable
$fields->enum('status', Status::class, required: true); // Status
string(),integer(),float(),boolean(),date(),enum()andarray()take it. Forenum(), it comes after the enum class.- A
nullvalue, sent asnullor not sent and without default, throwsInvalidFieldException. Give the input therequiredrule, asexpires_atin the action above.$fields->string('note', required: true)on anoteinput sent asnullgives:
The input [note] of App\Rest\Actions\CloseTickets::fields() is required, but its value is null. Add the required rule to the input.
- The conversion rules do not change, and a read without
requiredstill returnsnullfor anullvalue.
Results
Override respond() to answer the client with a result. It runs once, after the last chunk, and receives the fields and impacted:
use Lomkit\Rest\Actions\ActionFields;
use Lomkit\Rest\Actions\ActionResponse;
public function respond(ActionFields $fields, int $impacted): ?ActionResponse
{
return ActionResponse::message("{$impacted} subscriptions extended");
}
{"data": {"impacted": 11, "result": {"type": "message", "message": "11 subscriptions extended"}}}
respond() returns | result |
|---|---|
ActionResponse::message('Done') | {"type": "message", "message": "Done"} |
ActionResponse::danger('2 subscriptions are locked') | {"type": "danger", "message": "2 subscriptions are locked"} |
ActionResponse::download($url, 'subscriptions.csv') | {"type": "download", "url": "...", "name": "subscriptions.csv"} |
ActionResponse::redirect($url) | {"type": "redirect", "url": "..."} |
ActionResponse::created($invoices) | {"type": "created", "keys": [29, 30]} |
ActionResponse::data(['export' => 41, 'rows' => 120]) | {"type": "data", "data": {"export": 41, "rows": 120}} |
ActionResponse::message('Export started')->withData(['export' => 41]) | {"type": "message", "message": "Export started", "data": {"export": 41}} |
null, the default | null |
- The status stays
200. The package does not send the file or follow the URL: the client acts on the result. data()andwithData()take an array with string keys. A list throwsLomkit\Rest\Exceptions\InvalidActionException.respond()does not run whenhandle()throws.
Hints for clients
The $destructive and $confirm properties mark an action for clients:
public bool $destructive = true;
public ?string $confirm = 'Extend the selected subscriptions?';
On an instance, ->destructive() and ->confirm('Extend the selected subscriptions?') set them. The details give both on each action, with ?with=actions, and the OpenAPI operation of the action carries them as x-lomkit-destructive and x-lomkit-confirm. The endpoint runs the action the same way: to make the endpoint check a confirmation, see Confirmation.
Abilities
Before validation, a known action checks, in this order:
viewAnyon the resource;- the abilities that the resource's
abilities()returns forEndpoint::Operate, none by default; - the abilities that the action's
abilities()returns,['viewAny']by default.
public function abilities(): array
{
return ['export'];
}
These abilities add to viewAny: the action above checks viewAny, then export. An action whose abilities() returns [] runs without any of these checks, for an action that any user may run, guests included. The resources that its search reaches through includes and relation filters still need viewAny. See Policies.
Checking each row
authorizeEach() names a policy ability that the action checks on every row before it runs on any row:
public function authorizeEach(): ?string
{
return 'update';
}
A refused row answers 403 with the message of the first refusal, {"message": "Closed tickets are read-only."}, and no row is handled, no job is queued. To list every refused row in the body, see the denials of Policies.
- The action runs on the rows that passed the checks, and on no other: a row that the search did not match during the checks, or that another request adds after them, is left out.
- The checked rows count toward
$maxResources: the checks stop at the first chunk that goes over it, with the422of Capping the rows, and no row is handled.
With public bool $skipUnauthorized = true;, or ->skipUnauthorized() on an instance, the action runs on the allowed rows only, and impacted counts them. A queued action checks the rows in the request, not again in the worker.
skipUnauthorized()without an ability, or an ability on theNonetarget, throwsInvalidActionExceptionwhen the action is built: when the routes register for an instance, when it is first used for a class. See Declaration checks.php artisan rest:checkreports each action on theSearchorResourcestarget whoseauthorizeEach()returnsnull. An action that only reads returns'view'.
Chunks and transactions
The rows reach handle() in chunks of $chunkCount rows, 100 by default.
- A search without
sortsand withoutlimitreads the rows in the order of their key, chunk after chunk, so an action that changes a filtered column still reaches every row. - With
sortsor alimit, the action reads the keys first, in the order of the search, then loads each chunk of keys. - The
Resourcestarget gives the rows in the order ofresources.
The $transaction property chooses the transactions, on the connection of the model:
| Value | On an instance | Behaviour |
|---|---|---|
ActionTransaction::Chunk, the default | each chunk runs in its own transaction, also around handle() in a queued job | |
ActionTransaction::Whole | ->atomic() | every chunk runs in one transaction: a throw rolls back every row |
ActionTransaction::Row | ->transactionPerRow() | each row runs in its own transaction, in handleRow(), see below |
ActionTransaction::None | ->withoutTransaction() | no transaction: each row is written when handle() writes it |
use Lomkit\Rest\Actions\ActionTransaction;
public ActionTransaction $transaction = ActionTransaction::None;
- Use
Nonefor an action that calls an external service on each row or commits its own progress. respond()runs after the commit.Wholeon an action that implementsShouldQueuethrowsInvalidActionException: its chunks run in the worker, outside the request.- With
transactions.attemptsabove1inconfig/rest.php, a chunk, a row or a whole run that hits a deadlock runs again. See Deadlock retries.
One transaction per row
With ActionTransaction::Row, each row runs in its own transaction, in the request and in the jobs of a queued action, whatever $chunkCount. The rows reach handleRow() instead of handle(). beforeRow() runs just before, outside any transaction, for a call to an external service:
use Illuminate\Database\Eloquent\Model;
use Lomkit\Rest\Actions\Action;
use Lomkit\Rest\Actions\ActionFields;
use Lomkit\Rest\Actions\ActionTransaction;
class InvoiceOrders extends Action
{
public ActionTransaction $transaction = ActionTransaction::Row;
public function beforeRow(ActionFields $fields, Model $row): void
{
$this->billing->reserveInvoiceNumber($row);
}
public function handleRow(ActionFields $fields, Model $row): void
{
$row->update(['status' => 'invoiced']);
}
}
- When a row throws, its transaction is rolled back and the run, or the job, stops there. The rows before it stay written.
- A deadlock runs the transaction of the row again,
handleRow()included, but notbeforeRow(). - An action with
RowthrowsInvalidActionExceptionwhen it is built if it does not declarehandleRow(), if it declareshandle(), or if its target isNone. So does an action that declareshandleRow()orbeforeRow()withoutRow:
App\Rest\Actions\InvoiceOrders runs each row in its own transaction (ActionTransaction::Row), but it does not declare handleRow(): with Row, each row reaches handleRow(ActionFields $fields, Model $row) instead of handle().
Middleware
An action carries its own route middleware in the $middleware and $withoutMiddleware properties:
class ExportTickets extends Action
{
public array $middleware = ['throttle:exports'];
}
class ReportOutage extends Action
{
public array $withoutMiddleware = ['auth:sanctum'];
}
The route gets the package middleware, the middleware of the resource, the middleware of middlewareFor('operate', ...), then its own. $withoutMiddleware removes a middleware of any of these: name it as it is declared, with its parameters.
- For an action listed by its class, the package reads the default values of these properties when the routes register, without building the class. See Declaration checks.
- An instance takes
->middleware('throttle:exports')and->withoutMiddleware('auth:sanctum'). - After a change of the middleware, run
php artisan route:cacheagain, see Cached routes.
Declaration checks
When the routes register
InvalidActionException refuses, when the routes register:
- a class that overrides
name()oruriKey(): set$nameand$uriKeyinstead, or list the action as an instance; - an abstract class;
Action::classitself;- a class that does not extend
Action, such as a metric.
App\Rest\Actions\CloseTickets is listed by its class, but it overrides uriKey(): its route key must be read without building it. Set $uriKey for the route key and $name for the label, or list the action as an instance.
When the action is built
- An action listed by its class whose built instance has another key,
$middlewareor$withoutMiddlewarethan the defaults of its properties throwsInvalidActionExceptionand does not run. A constructor that calls$this->middleware()or sets$uriKey, or a promoted constructor parameter$middlewareor$uriKey, does that:
App\Rest\Actions\CloseTickets is listed by its class, but its built instance has another route key or other middleware than its class declares. Set $uriKey, $name, $middleware and $withoutMiddleware as property defaults, or list the action as an instance.
- A container binding that returns another class throws too, with a message that names the binding. A binding to a subclass with the same route runs that subclass.
- The other declaration errors of a class, such as
skipUnauthorized()without an ability, throw when it is first built, not when the routes register.php artisan rest:checkbuilds every action and metric and reports these errors: run it in CI.
Cached routes
Each action route records the key and the middleware that it was registered with, also through php artisan route:cache. An action, listed by its class or as an instance, that a request or a queued run builds with another key or other middleware throws InvalidActionException and does not run:
App\Rest\Actions\CloseTickets has another route key or other middleware than its route was registered with. Run php artisan route:cache again, or stop changing its route in its constructor.
Run php artisan route:cache again after you change the key or the middleware of an action.
Reading the request
Once the request passed validation, $this->request()->payload() returns a Lomkit\Rest\Actions\OperationNode: action, fields (the input values as sent) and target (the parsed search, the keys of resources, or null). The resource's operating() and operated() events run around the chunks, see Events and hooks.
Static analysis
Reading 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. With phpstan/extension-installer, PHPStan includes it. Without it, add it to the includes of your configuration:
includes:
- vendor/lomkit/laravel-rest-api/extension.neon
- A property is
mixedto PHPStan. Read an input with a typed reader when the code needs its type. - PHPStan does not require a constructor without arguments on an action, an instruction or a metric: an action that injects services passes.
- A subclass that redefines
make()withnew static(...)gets PHPStan's "Unsafe usage of new static()". Add/** @phpstan-consistent-constructor */on that class.
The model of an action
Action declares the model that it runs on as a template with a default, @template TModel of Model = Model. An action declares its own model with @extends, and narrows the parameters of handle():
use App\Models\Invoice;
use Illuminate\Support\Collection;
use Lomkit\Rest\Actions\Action;
use Lomkit\Rest\Actions\ActionFields;
/** @extends Action<Invoice> */
final class SendInvoices extends Action
{
/** @param Collection<array-key, Invoice> $models */
public function handle(ActionFields $fields, Collection $models): void
{
foreach ($models as $invoice) {
$invoice->update(['sent_at' => now()]);
}
}
}
- The template applies to
handle(),beforeRow()andhandleRow(). Narrow a row with@param Invoice $row. - An action without
@extendskeepsModeland gets no new PHPStan error at any level, including no "does not specify its types". - Instructions take the same template, see The model of an instruction.