# Scopes and instructions

> Let clients call the local scopes of a model and the instructions of a resource, with typed parameters, aliases and search meta.

Scopes and instructions let a client run query logic that the resource declares. A scope calls a local scope of the model with positional parameters. An instruction is a class of its own, with named fields, that changes the query of the search.

## Scopes

```php [app/Models/Post.php]
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Builder;

public function scopePublishedSince(Builder $query, CarbonImmutable $since): void
{
    $query->where('published_on', '>=', $since);
}

public function scopePopular(Builder $query, int $minViews): void
{
    $query->where('views', '>=', $minViews);
}
```

```php [app/Rest/Resources/PostResource.php]
use Lomkit\Rest\Fields\Date;
use Lomkit\Rest\Fields\Integer;
use Lomkit\Rest\Scopes\Scope;

public function scopes(): array
{
    return [
        Scope::make('publishedSince')->fields([Date::make('since')]),
        Scope::make('popular')->fields([Integer::make('min_views')->default(100)]),
    ];
}
```

```json [POST /api/posts/search]
{
  "search": {
    "scopes": [
      {"name": "publishedSince", "parameters": ["2026-01-01"]},
      {"name": "popular"}
    ]
  }
}
```

- `scopes()` returns `Scope` objects. Each one names a local scope of the model: a `scopeX()` method or a method with the `#[Scope]` attribute. Builder methods and macros, such as `withTrashed`, cannot be called as scopes.
- `fields()` declares the parameters, in the order of the arguments of the scope method.
- `parameters` is a positional list: each value binds to the field at the same position, is validated by the rules of that field, cast to its type and filled from its `default()`. A `Date` reaches the scope as a `CarbonImmutable` at the start of the day, a `DateTime` with an offset as a `CarbonImmutable` converted to `config('app.timezone')`, an `Integer` as an `int`.
- A position is required unless its field declares `default()`. A nullable field accepts an explicit `null`.
- A rule that names another field of the same scope, such as `gte:min`, compares with the parameter at that field's position.
- Each scope applies in its own group, joined to the rest of the search with `and`: an `orWhere()` in the scope does not widen the perimeter or the other filters.
- Includes take `scopes` too, with the scopes of the related resource.
- `meta([...])` on a scope adds keys to its entry in the [details](/digging-deeper/details), returned when the request asks for `with=scopes.meta`.

### Scope errors

<table>
<thead>
  <tr>
    <th>
      Message
    </th>
    
    <th>
      Cause
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        The selected search.scopes.0.name is invalid.
      </code>
    </td>
    
    <td>
      A scope that the resource does not declare
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        The search.scopes.0.parameters.0 field is required.
      </code>
    </td>
    
    <td>
      A missing position without <code>
        default()
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        The search.scopes.0.parameters.0 field must be a valid date.
      </code>
    </td>
    
    <td>
      A value that the field type refuses
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        The search.scopes.0.parameters field must not have more than 1 items.
      </code>
    </td>
    
    <td>
      More parameters than the scope declares
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        The search.scopes.0.parameters field must be a list.
      </code>
    </td>
    
    <td>
      Named parameters instead of a list
    </td>
  </tr>
</tbody>
</table>

In a search on a search engine, with a text or with `"source": "engine"`, `scopes` gives a 422, see [Search engines](/search/search-engines).

## Instructions

Generate an instruction:

```bash
php artisan rest:instruction PriceRange
```

```php [app/Rest/Instructions/PriceRange.php]
use Illuminate\Database\Eloquent\Builder;
use Lomkit\Rest\Fields\Integer;
use Lomkit\Rest\Instructions\Instruction;
use Lomkit\Rest\Instructions\InstructionFields;

class PriceRange extends Instruction
{
    public ?string $name = 'Price range';

    public function fields(): array
    {
        return [
            Integer::make('min')->default(0),
            Integer::make('max')->rules('required'),
        ];
    }

    public function handle(InstructionFields $fields, Builder $query): void
    {
        $query->whereBetween('price', [$fields->min, $fields->max]);
    }
}
```

List it by its class in the `instructions()` method of the resource:

```php [app/Rest/Resources/ProductResource.php]
use App\Rest\Instructions\PriceRange;

public function instructions(): array
{
    return [PriceRange::class];
}
```

```json [POST /api/products/search]
{
  "search": {
    "instructions": [
      {"name": "price-range", "fields": [{"name": "max", "value": 100}]}
    ]
  }
}
```

- `name` is the `uriKey()` of the instruction: the `$name` property in kebab case (`price-range`), or without it the class name without an `Instruction` suffix. `$name` is the label that the [details](/digging-deeper/details) give.
- `fields` is a list of `{"name", "value"}` entries. Each field is validated by its rules with the full Laravel validation, `required` on a missing field included, and filled from its `default()`.
- `handle()` receives an `InstructionFields`: read a value as a property (`$fields->max`), in a given type with a [typed reader](/actions-and-metrics/actions#typed-readers) (`$fields->integer('max')`), or with `has()`, `filled()`, `only()` and `toArray()`. A reader throws `InvalidFieldException` on a value of another type: `The input [max] of App\Rest\Instructions\PriceRange::fields() is [int], not [string].` for `$fields->string('max')`.
- A typed reader takes `required: true` to return the non-null type, `int` for `$fields->integer('max', required: true)`, and throws `InvalidFieldException` on a `null` value. `max` has the `required` rule, so the read never meets `null`. See [Required reads](/actions-and-metrics/actions#required-reads).
- Each instruction applies in its own group, joined to the rest of the search with `and`.
- Includes take `instructions` too, with the instructions of the related resource.
- `$this->meta([...])` in the constructor of an instruction, or `->meta([...])` on an [instance](#reusing-an-instruction-with-other-settings), adds keys to its entry in the [details](/digging-deeper/details), returned when the request asks for `with=instructions.meta`.

`rest:instruction` prints the line to add: `List it in the instructions() of a resource by its class: PriceRange::class.`

### Instructions that inject services

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

```php [app/Rest/Instructions/DueSoon.php]
use App\Support\WorkingDays;
use Illuminate\Database\Eloquent\Builder;
use Lomkit\Rest\Fields\Integer;
use Lomkit\Rest\Instructions\Instruction;
use Lomkit\Rest\Instructions\InstructionFields;

class DueSoon extends Instruction
{
    public ?string $name = 'Due soon';

    public function __construct(private readonly WorkingDays $workingDays) {}

    public function fields(): array
    {
        return [Integer::make('days')->default(5)];
    }

    public function handle(InstructionFields $fields, Builder $query): void
    {
        $query->where('due_on', '<=', $this->workingDays->after(today(), $fields->days));
    }
}
```

```php [app/Rest/Resources/TicketResource.php]
public function instructions(): array
{
    return [DueSoon::class];
}
```

- A parameter that the container cannot resolve throws when the instructions are read: `rest:check` builds every instruction and reports it, see [Declaration checks](#declaration-checks).
- `rest:check` builds the instruction without a user. Resolve what depends on the user, such as the tenant, when the instruction runs, in `handle()`.

### When the instructions are built

- Registering the routes reads no instruction. The container builds the listed classes the first time the resource reads its instructions in a request: a search that sends `instructions`, at its root, in an include of the resource or in the search of an action or a metric, and `/details`.
- A request that reads no instruction, such as a mutation or a search without `instructions`, builds none.
- Reading one instruction builds the whole list of the resource. Keep the constructors light, and do the work in `handle()`.
- Each class is built once per resource definition, that is once per request, and the list keeps its order. The [OpenAPI document](/digging-deeper/openapi) and [`rest:check`](/digging-deeper/artisan#checking-the-application) build their own.
- Instructions have no route, so an instruction listed by its class can override `name()` or `uriKey()`.
- The [details](/digging-deeper/details), the OpenAPI document and searches are the same for a class and the matching instance.

### Reusing an instruction with other settings

List an instance for an instruction built with arguments or reused with other settings, such as `PriceRange` in another resource. One list can mix both forms:

```php [app/Rest/Resources/OfferResource.php]
public function instructions(): array
{
    return [
        DueSoon::class,
        PriceRange::make()->meta(['unit' => 'EUR']),
    ];
}
```

- `->meta(['unit' => 'EUR'])` sets the meta on the instance.
- `make()` passes its arguments to the constructor, not through the container.

### Aliases

Each entry of one `instructions` list needs its own key: its `alias`, or else its `name`. To send one instruction twice, give one entry an `alias`:

```json [POST /api/products/search]
{
  "search": {
    "instructions": [
      {"name": "price-range", "fields": [{"name": "max", "value": 100}]},
      {"name": "price-range", "alias": "not_free", "fields": [{"name": "min", "value": 1}, {"name": "max", "value": 1000}]}
    ]
  }
}
```

- An alias looks like an identifier, `^[A-Za-z_][A-Za-z0-9_]*$`, of at most 255 characters.
- The same instruction twice without an alias gives a 422 under each repeated entry: `The search.instructions.1.alias field is required, because the key price-range is already used.`
- An alias that another entry uses, as its alias or its name, gives `The search.instructions.1.alias is already used by another instruction.`
- The rule holds at every level: includes, the search of an action and the search of a metric.
- The alias keys the meta of the instruction, below.

### Instruction meta

An instruction can add an object to the `meta` of the search page with `searchMeta()`:

```php [app/Rest/Instructions/Noted.php]
class Noted extends Instruction
{
    public function fields(): array
    {
        return [Integer::make('min_views')->nullable()];
    }

    public function handle(InstructionFields $fields, Builder $query): void
    {
        if ($fields->min_views !== null) {
            $query->where('views', '>=', $fields->min_views);
        }
    }

    public function searchMeta(InstructionFields $fields): array
    {
        if ($fields->min_views === null) {
            return [];
        }

        return ['notice' => "Lists the posts with {$fields->min_views} views or more."];
    }
}
```

```json [POST /api/posts/search]
{
  "search": {
    "instructions": [
      {"name": "noted", "fields": [{"name": "min_views", "value": 100}]},
      {"name": "noted", "alias": "busy", "fields": [{"name": "min_views", "value": 200}]}
    ]
  }
}
```

```json [200 OK]
{
  "current_page": 1,
  "data": [...],
  "from": 1,
  "last_page": 1,
  "per_page": 50,
  "to": 1,
  "total": 1,
  "meta": {
    "instructions": {
      "noted": {"notice": "Lists the posts with 100 views or more."},
      "busy": {"notice": "Lists the posts with 200 views or more."}
    }
  }
}
```

- Each instruction at the root of the search adds its object under `meta.instructions`, keyed by the `alias` of its entry, or else its name.
- An instruction that returns `[]` adds nothing, and `instructions` is left out when no instruction adds anything.
- The instructions of an include add nothing.
- `meta.instructions` comes after the `create` gate and the keys of the resource's `searchMeta()`, see [Meta](/search/overview#meta).

### Instruction errors

<table>
<thead>
  <tr>
    <th>
      Message
    </th>
    
    <th>
      Cause
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        The selected search.instructions.0.name is invalid.
      </code>
    </td>
    
    <td>
      An instruction that the resource does not declare
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        The selected search.instructions.0.fields.0.name is invalid.
      </code>
    </td>
    
    <td>
      A field that the instruction does not declare
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        The search.instructions.0.fields.1.name field has a duplicate value.
      </code>
    </td>
    
    <td>
      A field name sent twice
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        The price field must be an integer.
      </code>
    </td>
    
    <td>
      Under <code>
        search.instructions.0.fields.price
      </code>
      
      : a value that the rules of the field refuse
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        The search.instructions.0.fields field must be a list.
      </code>
    </td>
    
    <td>
      <code>
        fields
      </code>
      
       sent as an object
    </td>
  </tr>
</tbody>
</table>

Field errors go under `search.instructions.{index}.fields.{name}`, with the label of the field. Custom translation lines go under `validation.custom.search.instructions.*.fields.{name}.{rule}`.

### Declaration checks

When the instructions of a resource are read, `Lomkit\Rest\Exceptions\InvalidInstructionException` refuses:

- a name that is not a class extending `Instruction`;
- `Instruction::class` itself;
- an abstract class;
- a container binding that returns another class. A binding to a subclass runs that subclass.

Each message names the resource and the entry:

```text
App\Rest\Resources\ProductResource::instructions() lists App\Rest\Instructions\RangeInstruction, which is abstract or cannot be instantiated. List a concrete class.
```

A constructor parameter that the container cannot resolve throws when the instructions are read too. [`php artisan rest:check`](/digging-deeper/artisan#checking-the-application) builds every instruction and reports these errors: run it in CI.

### The model of an instruction

`Instruction` declares the model of its query as a PHPStan template with a default, `@template TModel of Model = Model`. An instruction declares its own model with `@extends`, and narrows the query of `handle()`:

```php [app/Rest/Instructions/Unpaid.php]
use App\Models\Invoice;
use Illuminate\Database\Eloquent\Builder;
use Lomkit\Rest\Instructions\Instruction;
use Lomkit\Rest\Instructions\InstructionFields;

/** @extends Instruction<Invoice> */
final class Unpaid extends Instruction
{
    /** @param Builder<Invoice> $query */
    public function handle(InstructionFields $fields, Builder $query): void
    {
        $query->whereNull('paid_at');
    }
}
```

- An instruction without `@extends` keeps `Model`, its query a `Builder<Model>`, and gets no new PHPStan error at any level.
- PHPStan reads the inputs of `InstructionFields` as properties through the `extension.neon` of the package, see [Static analysis](/actions-and-metrics/actions#static-analysis).

### Instructions on a search engine

An instruction that implements `Lomkit\Rest\Instructions\AppliesToEngine` also runs next to a text search on a search engine, and in an engine list, through `handleEngine()`. A value that it passes to the engine query and that the engine query refuses answers `422` under `search.instructions.N`. See [Search engines](/search/search-engines#instructions).

### Instructions from extensions

An [extension](/extensions/queries#declaring-instructions) that implements `DeclaresInstructions` adds instructions to a resource. Their key is the name of the extension, a dot and their `uriKey()`, such as `arc.with-archived`, in requests, `/details`, search meta and the OpenAPI document. `publicUriKey()` returns that key. It is a final method of `Instruction`: an instruction of your own cannot declare a method of that name.

## Decorating the rows

An instruction, or a scope from `scopes()`, can change the loaded rows with an Eloquent `afterQuery()` callback:

```php [app/Rest/Instructions/MarkLoadedPosts.php]
use App\Models\Post;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Lomkit\Rest\Instructions\Instruction;
use Lomkit\Rest\Instructions\InstructionFields;

class MarkLoadedPosts extends Instruction
{
    public function handle(InstructionFields $fields, Builder $query): void
    {
        $query->afterQuery(function (Collection $posts): void {
            $posts->each(function (Post $post): void {
                $post->setAttribute('title', "{$post->getAttribute('title')} (loaded)");
            });
        });
    }
}
```

The callback receives an `Illuminate\Database\Eloquent\Collection` for each batch of rows that the package loads: the page of a search, each chunk of an [export](/search/outside-http#lazy-and-exports) or of an [action](/actions-and-metrics/actions#chunks-and-transactions), the rows of an include. It never receives keys or counts. It must not filter or reorder the rows, because totals and chunks are counted in SQL. A callback registered inside `perimeterQuery()` is not kept.

## Limits

<table>
<thead>
  <tr>
    <th>
      Limit
    </th>
    
    <th>
      Default
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        rest.limits.sizes.scopes
      </code>
    </td>
    
    <td>
      10 scopes per list
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        rest.limits.sizes.instructions
      </code>
    </td>
    
    <td>
      10 instructions per list
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        rest.limits.sizes.fields
      </code>
    </td>
    
    <td>
      100 fields per instruction
    </td>
  </tr>
</tbody>
</table>

The `parameters` of a scope keep their own limit: one value per field of the scope.
