Actions and Metrics

Actions

Run your own code on the rows of a resource, with typed inputs, row checks, transactions and a result for the client.

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 Action suffix: ExtendSubscriptions gives the name Extend Subscriptions and the key extend-subscriptions. Set the $name property to choose another name, and $uriKey for another key, see Route key and name.
  • Rest::resource() reads actions() when it registers the routes, without a user. Keep the list the same for every user and free of queries, and run php artisan route:cache again 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 operate request for its key, /details, the OpenAPI document, rest:check or a queued run. A request for another action does not build it.
  • Inside an action, $this->resource is 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:

app/Rest/Actions/CloseTickets.php
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;
}
PropertySetsPage
$name, $uriKeythe name in /details and the key of the routeRoute key and name
$targetthe rows that the action runs onTargets
$maxResourcesthe most rows that one run reachesCapping the rows
$destructive, $confirmthe hints for clientsHints for clients
$skipUnauthorizedruns on the allowed rows onlyChecking each row
$chunkCount, $transactionthe size of the chunks and the transactionsChunks and transactions
$middleware, $withoutMiddlewarethe middleware of the routeMiddleware

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 key end. Without both, it comes from the class name: CloseTickets gives close-tickets.
  • $uriKey works on an instance too.
  • Two actions of one resource with one key throw Lomkit\Rest\Exceptions\InvalidResourceRouteException when the routes register.

Actions that inject services

The container builds an action listed by its class, so its constructor can inject services:

app/Rest/Actions/InvoiceOrders.php
class InvoiceOrders extends Action
{
    public function __construct(private readonly Billing $billing) {}
}
app/Rest/Resources/OrderResource.php
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:check builds every action and reports it.
  • rest:check builds the action without a user. Resolve what depends on the user, such as the tenant, when the action runs, in handle().
  • 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 /details first 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}}
  • fields is a list of {name, value} entries, not an object keyed by name. An object is a 422: The fields field must be a list. Each name appears once, and an entry takes name and value only.
  • impacted is the number of rows that the action ran on: the rows given to handle(), or the rows put into the jobs of a queued action.
  • An unknown action answers 404 to a user allowed viewAny on the resource, and 403 to 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).

TargetsearchresourcesRows
ActionTarget::Search, the defaultrequiredrefusedthe rows that search matches inside the perimeter, every row with "search": {}
ActionTarget::Resourcesrefusedrequiredthe rows of the keys in resources, in their order
ActionTarget::Nonerefusedrefusednone: handle() receives an empty collection
With the 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"}]}
  • search takes the keys of a search, without page, as an object. text works on a resource that declares a text search.
  • A key of resources that does not exist, or that perimeterQuery() leaves out, is a 422 under resources.{index}. A repeated key is a 422 too. A key outside the perimeter also dispatches the KeysOutOfReach event.
  • 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_if and present fire even when the field is absent from fields.
  • An error is keyed by the field name, fields.expires_at. An unknown or repeated name is reported by position, fields.0.name.
  • An Enum field 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.fields entries, 100 by 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:

ReadGives
$fields->expires_ata 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 null when the value is null: sent as null, or not sent and without default.
  • date() reads a Date field, and a DateTime field in config('app.timezone').
  • float() also converts an int or a numeric string: a Number sent as "19.99" gives 19.99. integer() converts a string that is exactly an integer: "3" gives 3, 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 that fields() 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->price on a Number sent as "19.99" stays that string. has(), filled(), only() and toArray() 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() and array() take it. For enum(), it comes after the enum class.
  • A null value, sent as null or not sent and without default, throws InvalidFieldException. Give the input the required rule, as expires_at in the action above. $fields->string('note', required: true) on a note input sent as null gives:
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 required still returns null for a null value.

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() returnsresult
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 defaultnull
  • The status stays 200. The package does not send the file or follow the URL: the client acts on the result.
  • data() and withData() take an array with string keys. A list throws Lomkit\Rest\Exceptions\InvalidActionException.
  • respond() does not run when handle() 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:

  1. viewAny on the resource;
  2. the abilities that the resource's abilities() returns for Endpoint::Operate, none by default;
  3. 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 the 422 of 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 the None target, throws InvalidActionException when 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:check reports each action on the Search or Resources target whose authorizeEach() returns null. 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 sorts and without limit reads the rows in the order of their key, chunk after chunk, so an action that changes a filtered column still reaches every row.
  • With sorts or a limit, the action reads the keys first, in the order of the search, then loads each chunk of keys.
  • The Resources target gives the rows in the order of resources.

The $transaction property chooses the transactions, on the connection of the model:

ValueOn an instanceBehaviour
ActionTransaction::Chunk, the defaulteach 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 None for an action that calls an external service on each row or commits its own progress.
  • respond() runs after the commit.
  • Whole on an action that implements ShouldQueue throws InvalidActionException: its chunks run in the worker, outside the request.
  • With transactions.attempts above 1 in config/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 not beforeRow().
  • An action with Row throws InvalidActionException when it is built if it does not declare handleRow(), if it declares handle(), or if its target is None. So does an action that declares handleRow() or beforeRow() without Row:
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:cache again, see Cached routes.

Declaration checks

When the routes register

InvalidActionException refuses, when the routes register:

  • a class that overrides name() or uriKey(): set $name and $uriKey instead, or list the action as an instance;
  • an abstract class;
  • Action::class itself;
  • 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, $middleware or $withoutMiddleware than the defaults of its properties throws InvalidActionException and does not run. A constructor that calls $this->middleware() or sets $uriKey, or a promoted constructor parameter $middleware or $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:check builds 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:

phpstan.neon
includes:
    - vendor/lomkit/laravel-rest-api/extension.neon
  • A property is mixed to 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() with new 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():

app/Rest/Actions/SendInvoices.php
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() and handleRow(). Narrow a row with @param Invoice $row.
  • An action without @extends keeps Model and 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.