# Events and Hooks

> Run your code at fixed moments of each endpoint with resource events and row hooks, and listen to the Laravel events of each write.

The package gives you three ways to run your code around an endpoint:

- **Resource events**, such as `searching()` or `destroyedAll()`: methods of the resource that run once per request, at a fixed moment.
- **Row hooks**, such as `mutating()` or `destroyed()`: methods of the resource that run for each row.
- **Laravel events**, such as `ResourceMutated`: dispatched once a write is committed, for every resource.

## Resource events

Override the event on the resource. Each one receives a typed payload and returns nothing:

<table>
<thead>
  <tr>
    <th>
      Event
    </th>
    
    <th>
      When it runs
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        describing(): void
      </code>
    </td>
    
    <td>
      once <code>
        viewAny
      </code>
      
       passed, before the details are built
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        described(array $details): void
      </code>
    </td>
    
    <td>
      after the details are built
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        searching(SearchContext $search): void
      </code>
    </td>
    
    <td>
      after validation, before any query; also for the search of an action or a metric
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        searched(LengthAwarePaginator $page): void
      </code>
    </td>
    
    <td>
      after the query and the includes are read, before the rows are rendered
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        mutatingAll(array $entries): void
      </code>
    </td>
    
    <td>
      inside the transaction, after the row checks, before the first write
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        mutatedAll(array $operations): void
      </code>
    </td>
    
    <td>
      inside the transaction, after the last write
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        operating(Action $action, ActionFields $fields): void
      </code>
    </td>
    
    <td>
      after the row checks of the action, before the first chunk
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        operated(Action $action, ActionFields $fields, int $impacted): void
      </code>
    </td>
    
    <td>
      after the last chunk, before <code>
        respond()
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        destroyingAll(Collection $models)
      </code>
      
      , <code>
        restoringAll()
      </code>
      
      , <code>
        forceDestroyingAll()
      </code>
    </td>
    
    <td>
      inside the transaction, after the row checks, before the first row
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        destroyedAll(Collection $models)
      </code>
      
      , <code>
        restoredAll()
      </code>
      
      , <code>
        forceDestroyedAll()
      </code>
    </td>
    
    <td>
      inside the transaction, after the last row
    </td>
  </tr>
</tbody>
</table>

- The events run after the entry checks and the validation. The events that receive rows also run after the row checks: a row that a policy refuses runs no event.
- An event that throws stops the endpoint. A `ValidationException` gives a `422`, an `AuthorizationException` a `403`. Inside a transaction, the throw rolls it back: `mutatedAll()` and `destroyedAll()` can undo the write.
- An event cannot change what the endpoint does: its payload is read-only. Read the request with `$this->request()`.
- `operating()` and `operated()` run inside the transaction of an action with `ActionTransaction::Whole`. Otherwise each chunk is committed, or each row with `ActionTransaction::Row` and `ActionTransaction::None`, and a throw in `operated()` leaves the rows written and skips `respond()`.
- The queued jobs of an action run no event: the events run in the request.

### Refusing a search

`searching()` receives a `Lomkit\Rest\Search\SearchContext` built from the validated search. Throw a `ValidationException` to refuse it before any query:

```php
use Illuminate\Validation\ValidationException;
use Lomkit\Rest\Search\SearchContext;

public function searching(SearchContext $search): void
{
    if ($search->filtersOn('from') && ! $search->filtersOn('to')) {
        throw ValidationException::withMessages(['search.filters' => 'The from filter requires a to filter.']);
    }
}
```

`filtersOn()` and `sortsOn()` take a field, a relation path such as `author.last_name`, or the key of an aggregate. `scopes()` and `includes()` list the names of the scopes and includes. The check also applies to the search of an action and of a metric.

### Logging a deletion

```php
use Illuminate\Database\Eloquent\Collection;

public function destroyedAll(Collection $tickets): void
{
    ActivityLog::record('tickets.destroyed', $tickets->modelKeys());
}
```

## Row hooks

Row hooks run for each row, inside the transaction of their endpoint:

<table>
<thead>
  <tr>
    <th>
      Hook
    </th>
    
    <th>
      When it runs
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        mutating(MutationNode $entry, Model $model): void
      </code>
    </td>
    
    <td>
      before a row of <code>
        mutate
      </code>
      
       is saved
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        mutated(MutationNode $entry, Model $model): void
      </code>
    </td>
    
    <td>
      after a row of <code>
        mutate
      </code>
      
       is saved
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        destroying(Model $model)
      </code>
      
      , <code>
        destroyed(Model $model)
      </code>
    </td>
    
    <td>
      around the deletion of each row
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        restoring(Model $model)
      </code>
      
      , <code>
        restored(Model $model)
      </code>
    </td>
    
    <td>
      around the restore of each row
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        forceDestroying(Model $model)
      </code>
      
      , <code>
        forceDestroyed(Model $model)
      </code>
    </td>
    
    <td>
      around the force deletion of each row
    </td>
  </tr>
</tbody>
</table>

`mutating()` and `mutated()` receive the entry of the request as a `Lomkit\Rest\Mutations\MutationNode`: `operation`, `key`, `attributes`, `pivot`, `withoutDetaching`, `relations`, `type`, `depth` and `path`.

```php
use Illuminate\Database\Eloquent\Model;
use Lomkit\Rest\Fields\MutationOperation;
use Lomkit\Rest\Mutations\MutationNode;

public function mutating(MutationNode $entry, Model $model): void
{
    if ($entry->operation === MutationOperation::Create) {
        $model->setAttribute('created_by', $this->request()->user()->id);
    }
}
```

- `mutating()` and `mutated()` run for each row that an entry writes, at every level: a `create`, an `update`, an entry with `attributes`, and an `attach`, `detach`, `sync` or `toggle` entry whose own `relations` change. They do not run for a target that is only linked, without `attributes` or `relations`.
- To keep a history row for each written row, write it in these hooks: see [Recording each written row](/writing/mutate#recording-each-written-row).
- `performDelete(Model $model)`, `performRestore(Model $model)` and `performForceDelete(Model $model)` replace the write itself.
- A `delete` entry of a `deletable()` relation in `mutate` goes through `performDelete()` and runs no `destroying()` or `destroyed()` hook.

### Columns that a hook fills

For each row of `mutate`, the hooks and the writes run in this order:

1. The `BelongsTo` and `MorphTo` entries of the row are written.
2. `mutating()` runs.
3. The attributes that the client sends are filled on the model, and the row is saved.
4. The other relations of the row are written, the pivot rows of its many-to-many relations included.
5. `mutated()` runs.

A value that the client sends is filled after `mutating()`, so it overwrites a value that the hook set on the same column. A column that the hook fills must not also be a writable field: declare it `readonly()`, `creatable(false)` or `updatable(false)`, or leave it out of `fields()`. For the hook above:

```php
Integer::make('created_by')->readonly(),
```

### Reading input-only values

`$entry->attributes` holds the values of the [`inputOnly()`](/resources/fields#input-only-fields) fields that the entry sends, next to the other attributes, in `mutating()` and in `mutated()`. The model never receives them:

```php
use App\Models\Shipment;
use Illuminate\Database\Eloquent\Model;
use Lomkit\Rest\Mutations\MutationNode;

public function mutated(MutationNode $entry, Model $model): void
{
    $address = $entry->attributes['delivery_address'] ?? null;

    if ($address !== null) {
        Shipment::create(['order_id' => $model->getKey(), 'address' => $address]);
    }
}
```

- For `{"quantity": 3, "delivery_address": "4 Mill Lane"}` on `update`, both hooks receive these two keys, and the model gets `quantity` only.
- An entry that sends only input-only values runs its hooks, and saves no column unless a hook sets one.
- The `update` policy sees the value in its `Changes`. The draft of the `create` policy does not hold it: refuse the value of a created row with rules, or in `mutating()`.

### Pivot rows

The pivot rows of a many-to-many relation are written before `mutated()` of the parent row runs, and a hook cannot change how they are written. To write them another way, such as keeping a withdrawn row, declare a [pivot persister](/resources/relations#pivot-persisters) on the relation with `persistedBy()`.

- The persister runs inside the transaction of the mutation, after the row checks, and before `mutated()` of the parent row.
- A `ValidationException` that it throws gives a `422`, an `AuthorizationException` a `403`, and the whole mutation rolls back.
- A [deadlock retry](/writing/mutate#deadlock-retries) runs it again: send mails, HTTP calls and jobs after the commit.

## Laravel events

After each write, the package dispatches a Laravel event, for every resource:

<table>
<thead>
  <tr>
    <th>
      Event (<code>
        Lomkit\Rest\Events
      </code>
      
      )
    </th>
    
    <th>
      Endpoint
    </th>
    
    <th>
      Properties
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        ResourceMutated
      </code>
    </td>
    
    <td>
      <code>
        mutate
      </code>
    </td>
    
    <td>
      <code>
        resource
      </code>
      
      , <code>
        operations
      </code>
      
       (the <code>
        operations
      </code>
      
       of the response, as arrays)
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ResourceDestroyed
      </code>
      
      , <code>
        ResourceForceDestroyed
      </code>
    </td>
    
    <td>
      <code>
        destroy
      </code>
      
      , <code>
        forceDestroy
      </code>
    </td>
    
    <td>
      <code>
        resource
      </code>
      
      , <code>
        model
      </code>
      
       (the class of the model), <code>
        keys
      </code>
      
       (the keys of the rows, in the order of <code>
        resources
      </code>
      
      )
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ResourceRestored
      </code>
    </td>
    
    <td>
      <code>
        restore
      </code>
    </td>
    
    <td>
      <code>
        resource
      </code>
      
      , <code>
        models
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        ActionOperated
      </code>
    </td>
    
    <td>
      <code>
        operate
      </code>
    </td>
    
    <td>
      <code>
        resource
      </code>
      
      , <code>
        action
      </code>
      
       (the class of the action), <code>
        uriKey
      </code>
      
      , <code>
        fields
      </code>
      
       (the values of the fields, by name), <code>
        impacted
      </code>
      
      , <code>
        batch
      </code>
      
       (the id of the batch, or <code>
        null
      </code>
      
      )
    </td>
  </tr>
</tbody>
</table>

```php
use Illuminate\Support\Facades\Event;
use Lomkit\Rest\Events\ResourceDestroyed;

Event::listen(ResourceDestroyed::class, function (ResourceDestroyed $event) {
    if ($event->resource === TicketResource::class) {
        ActivityLog::record($event->resource, 'destroyed', $event->keys);
    }
});
```

- `resource` is the class of the resource: filter on it.
- The event is dispatched once the write is committed, once per request: never for a write that rolls back, nor for an attempt that a deadlock runs again. The events implement `ShouldDispatchAfterCommit`.
- `ActionOperated` is dispatched once the run ends without error. For a queued action, it is dispatched in the request, once the jobs are queued. The queued jobs dispatch no event.
- Searches, details and metrics dispatch no event.
- A listener cannot refuse or change the write: refuse it in the resource events.
- A listener may implement `ShouldQueue`. `ResourceDestroyed` and `ResourceForceDestroyed` carry keys, since a deleted row may no longer load.

### Keys out of reach

When a request names keys that the [`perimeterQuery()`](/resources/perimeter) of their resource does not return, the package dispatches `Lomkit\Rest\Events\KeysOutOfReach`, so that a listener can record it. The request still answers its `422`, `The selected resources.1 is invalid.`:

```php
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Lomkit\Rest\Events\KeysOutOfReach;

Event::listen(KeysOutOfReach::class, function (KeysOutOfReach $event) {
    Log::warning('Keys out of reach', [
        'resource' => $event->resource,
        'endpoint' => $event->endpoint->value,
        'keys' => $event->keys,
        'paths' => $event->paths,
        'user' => $event->user,
    ]);
});
```

<table>
<thead>
  <tr>
    <th>
      Property
    </th>
    
    <th>
      Value
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        resource
      </code>
    </td>
    
    <td>
      the class of the resource of the keys
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        model
      </code>
    </td>
    
    <td>
      the class of its model
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        endpoint
      </code>
    </td>
    
    <td>
      the <code>
        Lomkit\Rest\Http\Routing\Endpoint
      </code>
      
       of the request, such as <code>
        Endpoint::Destroy
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        keys
      </code>
    </td>
    
    <td>
      the keys out of reach, each once, at most 50
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        paths
      </code>
    </td>
    
    <td>
      the payload path of each refused key, such as <code>
        mutate.0.relations.shelves.0.key.0
      </code>
      
      , at most 50
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        capped
      </code>
    </td>
    
    <td>
      <code>
        true
      </code>
      
       when keys or paths were left out
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        guard
      </code>
    </td>
    
    <td>
      the guard of the request
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        user
      </code>
    </td>
    
    <td>
      the identifier of the user, or <code>
        null
      </code>
      
       for a guest
    </td>
  </tr>
</tbody>
</table>

- It covers the `key` of a `mutate` entry and of a relation entry (`attach`, `detach`, `update`, `sync`, `toggle`, `delete`), the `resources` of an action, and the `resources` of `destroy`, `restore` and `forceDestroy`.
- One event per resource and per request, dispatched during validation, before the `422`. The response does not change.
- A key refused for another reason, its type, a repeat or a list over its limit, dispatches nothing.
- A [Precognition](/digging-deeper/precognition) request dispatches it when it validates the keys.
