# 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`:

```bash
php artisan rest:action ExtendSubscriptions
```

```php
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:

```php
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](#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](/digging-deeper/openapi), `rest:check` or a [queued run](/actions-and-metrics/queued-actions). 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:

```php [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;
}
```

<table>
<thead>
  <tr>
    <th>
      Property
    </th>
    
    <th>
      Sets
    </th>
    
    <th>
      Page
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        $name
      </code>
      
      , <code>
        $uriKey
      </code>
    </td>
    
    <td>
      the name in <code>
        /details
      </code>
      
       and the key of the route
    </td>
    
    <td>
      <a href="#route-key-and-name">
        Route key and name
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $target
      </code>
    </td>
    
    <td>
      the rows that the action runs on
    </td>
    
    <td>
      <a href="#targets">
        Targets
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $maxResources
      </code>
    </td>
    
    <td>
      the most rows that one run reaches
    </td>
    
    <td>
      <a href="#capping-the-rows">
        Capping the rows
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $destructive
      </code>
      
      , <code>
        $confirm
      </code>
    </td>
    
    <td>
      the hints for clients
    </td>
    
    <td>
      <a href="#hints-for-clients">
        Hints for clients
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $skipUnauthorized
      </code>
    </td>
    
    <td>
      runs on the allowed rows only
    </td>
    
    <td>
      <a href="#checking-each-row">
        Checking each row
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $chunkCount
      </code>
      
      , <code>
        $transaction
      </code>
    </td>
    
    <td>
      the size of the chunks and the transactions
    </td>
    
    <td>
      <a href="#chunks-and-transactions">
        Chunks and transactions
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $middleware
      </code>
      
      , <code>
        $withoutMiddleware
      </code>
    </td>
    
    <td>
      the middleware of the route
    </td>
    
    <td>
      <a href="#middleware">
        Middleware
      </a>
    </td>
  </tr>
</tbody>
</table>

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](#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:

```php
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:

```php [app/Rest/Actions/InvoiceOrders.php]
class InvoiceOrders extends Action
{
    public function __construct(private readonly Billing $billing) {}
}
```

```php [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](/search/scopes-and-instructions#instructions-that-inject-services).

### Reusing an action with other settings

List an instance when one action class serves several resources with other settings:

```php
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](/digging-deeper/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}`:

```http
POST /api/subscriptions/actions/extend-subscriptions
```

```json
{
  "fields": [{"name": "expires_at", "value": "2027-01-31"}],
  "search": {"filters": [{"field": "status", "value": "active"}]}
}
```

```json
{"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](/actions-and-metrics/queued-actions).
- 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:

```php
use Lomkit\Rest\Actions\ActionTarget;

class DeactivateUsers extends Action
{
    public ActionTarget $target = ActionTarget::Resources;
}
```

An [instance reused with other settings](#reusing-an-action-with-other-settings) sets it with `->target()`: `SendDigest::make()->target(ActionTarget::None)`.

<table>
<thead>
  <tr>
    <th>
      Target
    </th>
    
    <th>
      <code>
        search
      </code>
    </th>
    
    <th>
      <code>
        resources
      </code>
    </th>
    
    <th>
      Rows
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        ActionTarget::Search
      </code>
      
      , the default
    </td>
    
    <td>
      required
    </td>
    
    <td>
      refused
    </td>
    
    <td>
      the rows that <code>
        search
      </code>
      
       matches inside the <a href="/resources/perimeter">
        perimeter
      </a>
      
      , every row with <code>
        "search": {}
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ActionTarget::Resources
      </code>
    </td>
    
    <td>
      refused
    </td>
    
    <td>
      required
    </td>
    
    <td>
      the rows of the keys in <code>
        resources
      </code>
      
      , in their order
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ActionTarget::None
      </code>
    </td>
    
    <td>
      refused
    </td>
    
    <td>
      refused
    </td>
    
    <td>
      none: <code>
        handle()
      </code>
      
       receives an empty collection
    </td>
  </tr>
</tbody>
</table>

<note>

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.

</note>

```json
{"resources": [1, 5, 9], "fields": [{"name": "reason", "value": "spam"}]}
```

- `search` takes the keys of a [search](/search/overview), 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`](/digging-deeper/events-and-hooks#keys-out-of-reach) event.
- The [details](/digging-deeper/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.`

```php
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](/resources/fields). 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:

<table>
<thead>
  <tr>
    <th>
      Read
    </th>
    
    <th>
      Gives
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        $fields->expires_at
      </code>
    </td>
    
    <td>
      a <code>
        CarbonImmutable
      </code>
      
       for a <code>
        Date
      </code>
      
      , or for a <code>
        DateTime
      </code>
      
       in <code>
        config('app.timezone')
      </code>
      
      , the case for an <code>
        Enum
      </code>
      
      , <code>
        null
      </code>
      
       when not sent and without default
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $fields->has('reason')
      </code>
    </td>
    
    <td>
      <code>
        true
      </code>
      
       when the client sent it, <code>
        null
      </code>
      
       included, or when the field has a default
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $fields->filled('reason')
      </code>
    </td>
    
    <td>
      <code>
        has()
      </code>
      
       and not <code>
        null
      </code>
      
      , like <code>
        isset($fields->reason)
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $fields->only('plan', 'reason')
      </code>
      
      , <code>
        $fields->toArray()
      </code>
    </td>
    
    <td>
      the inputs that <code>
        has()
      </code>
      
       reports, by name
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $fields->user()
      </code>
    </td>
    
    <td>
      the user who sent the request, also in a queued job
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        $fields->target()
      </code>
    </td>
    
    <td>
      the <code>
        ActionTarget
      </code>
      
       of the action
    </td>
  </tr>
</tbody>
</table>

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

```php
$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:

```text
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:

```php
$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:

```text
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`:

```php
use Lomkit\Rest\Actions\ActionFields;
use Lomkit\Rest\Actions\ActionResponse;

public function respond(ActionFields $fields, int $impacted): ?ActionResponse
{
    return ActionResponse::message("{$impacted} subscriptions extended");
}
```

```json
{"data": {"impacted": 11, "result": {"type": "message", "message": "11 subscriptions extended"}}}
```

<table>
<thead>
  <tr>
    <th>
      <code>
        respond()
      </code>
      
       returns
    </th>
    
    <th>
      <code>
        result
      </code>
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        ActionResponse::message('Done')
      </code>
    </td>
    
    <td>
      <code>
        {"type": "message", "message": "Done"}
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ActionResponse::danger('2 subscriptions are locked')
      </code>
    </td>
    
    <td>
      <code>
        {"type": "danger", "message": "2 subscriptions are locked"}
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ActionResponse::download($url, 'subscriptions.csv')
      </code>
    </td>
    
    <td>
      <code>
        {"type": "download", "url": "...", "name": "subscriptions.csv"}
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ActionResponse::redirect($url)
      </code>
    </td>
    
    <td>
      <code>
        {"type": "redirect", "url": "..."}
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ActionResponse::created($invoices)
      </code>
    </td>
    
    <td>
      <code>
        {"type": "created", "keys": [29, 30]}
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ActionResponse::data(['export' => 41, 'rows' => 120])
      </code>
    </td>
    
    <td>
      <code>
        {"type": "data", "data": {"export": 41, "rows": 120}}
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ActionResponse::message('Export started')->withData(['export' => 41])
      </code>
    </td>
    
    <td>
      <code>
        {"type": "message", "message": "Export started", "data": {"export": 41}}
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        null
      </code>
      
      , the default
    </td>
    
    <td>
      <code>
        null
      </code>
    </td>
  </tr>
</tbody>
</table>

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

```php
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](/digging-deeper/details) give both on each action, with `?with=actions`, and the [OpenAPI](/digging-deeper/openapi#actions-and-writes) 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](/actions-and-metrics/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.

```php
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](/authorization/policies).

### Checking each row

`authorizeEach()` names a policy ability that the action checks on every row before it runs on any row:

```php
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](/authorization/policies#denials).

- 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](#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](#declaration-checks).
- [`php artisan rest:check`](/digging-deeper/artisan#checking-the-application) 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:

<table>
<thead>
  <tr>
    <th>
      Value
    </th>
    
    <th>
      On an instance
    </th>
    
    <th>
      Behaviour
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        ActionTransaction::Chunk
      </code>
      
      , the default
    </td>
    
    <td>
      
    </td>
    
    <td>
      each chunk runs in its own transaction, also around <code>
        handle()
      </code>
      
       in a queued job
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ActionTransaction::Whole
      </code>
    </td>
    
    <td>
      <code>
        ->atomic()
      </code>
    </td>
    
    <td>
      every chunk runs in one transaction: a throw rolls back every row
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ActionTransaction::Row
      </code>
    </td>
    
    <td>
      <code>
        ->transactionPerRow()
      </code>
    </td>
    
    <td>
      each row runs in its own transaction, in <code>
        handleRow()
      </code>
      
      , see <a href="#one-transaction-per-row">
        below
      </a>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ActionTransaction::None
      </code>
    </td>
    
    <td>
      <code>
        ->withoutTransaction()
      </code>
    </td>
    
    <td>
      no transaction: each row is written when <code>
        handle()
      </code>
      
       writes it
    </td>
  </tr>
</tbody>
</table>

```php
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](/writing/mutate#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](/actions-and-metrics/queued-actions), whatever `$chunkCount`. The rows reach `handleRow()` instead of `handle()`. `beforeRow()` runs just before, outside any transaction, for a call to an external service:

```php
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`:

```text
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:

```php
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](#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](#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.

```text
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:

```text
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`](/digging-deeper/artisan#checking-the-application) 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:

```text
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](/digging-deeper/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:

```yaml [phpstan.neon]
includes:
    - vendor/lomkit/laravel-rest-api/extension.neon
```

- A property is `mixed` to PHPStan. Read an input with a [typed reader](#typed-readers) 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](#actions-that-inject-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()`:

```php [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](/search/scopes-and-instructions#the-model-of-an-instruction).
