# Search overview

> A controlled Laravel Scout search keeps, in one engine query, the documents the reader may view: each document carries the keys that open it.

```php [app/Access/Controls/PostControl.php]
protected function perimeters(): array
{
    return [
        Levels::of(
            GlobalPerimeter::new()
                ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} all posts"))
                ->unrestricted(),
            ClientPerimeter::new()
                ->allowed(fn (User $user, Ability $ability) => $user->client_id !== null && $user->can("{$ability} client posts"))
                ->query(fn (Builder $query, User $user) => $query->where('client_id', $user->client_id))
                ->searchKeys(
                    name: 'client',
                    row: fn (Post $post) => $post->client_id,
                    reader: fn (User $user) => $user->client_id,
                ),
            OwnPerimeter::new()
                ->allowed(fn (User $user, Ability $ability) => $user->can("{$ability} own posts"))
                ->query(fn (Builder $query, User $user) => $query->where('author_id', $user->id))
                ->searchKeys(
                    name: 'author',
                    row: fn (Post $post) => $post->author_id,
                    reader: fn (User $user) => $user->id,
                ),
        ),
    ];
}
```

```php [app/Models/Post.php]
use Lomkit\Access\Controls\HasControl;
use Lomkit\Access\Search\ControlledSearchable;

class Post extends Model
{
    use HasControl, ControlledSearchable;
}
```

```php
Post::search('budget')->controlled()->paginate(25);
```

A controlled search is **one query to the search engine**, with all the filtering inside it:

- each document is indexed with the keys that open it: `client.7` and `author.42` for a post of client 7 written by user 42;
- each reader has keys: `client.7` for a manager of client 7 who reaches the client level, `author.42` for user 42 at the own level;
- the search keeps the documents that share at least one key with the reader.

The keys of every perimeter the reader reaches add up, so one filter gives the union of the perimeters, with the [levels](/essentials/levels) and the [boundary](#the-boundary) applied as in SQL.

## The model

Use `ControlledSearchable` instead of Scout's `Searchable`: the trait includes it. `toSearchableArray()` does not change: the keys are added to each document as Scout metadata, the way Scout adds `__soft_deleted`.

A model that overrides `makeSearchableUsing()` returns `$this->withAccessKeys($models)`, or its documents carry no keys and no controlled search finds them:

```php
public function makeSearchableUsing(Collection $models): Collection
{
    return $this->withAccessKeys($models->load('tags'));
}
```

Calling `controlled()` on the search of a model that still uses `Searchable` throws `MissingControlledSearchableException`.

## Search keys

Each perimeter that restricts rows declares its keys with `searchKeys()`, at the end of its chain:

```php
->searchKeys(
    name: 'client',
    row: fn (Post $post) => $post->client_id,
    reader: fn (User $user) => $user->client_id,
)
```

- `name` is required: lowercase letters, digits and underscores, unique in the control. Each key is prefixed with it, such as `client.7`, so two perimeters never open each other's rows. An invalid name throws `InvalidSearchKeyNameException`, a duplicate `DuplicateSearchKeyNameException`.
- `row` gives the keys of a row, when it is indexed. `reader` gives the keys of a reader, at each search.
- Each side returns a value, a list of values or a list of tuples: `[3, 7]` gives `client.3` and `client.7`, `[['fr', 7]]` gives `client.fr.7`. A value is an int, a string or a backed enum; anything else throws `InvalidSearchKeyValueException`.
- `null` gives no key, never a key that matches `null`. A reader without any key finds nothing.

### Relations

A `row` callback that reads a relation declares it in `load`:

```php
->searchKeys(
    name: 'shared',
    row: fn (Post $post) => $post->sharedWith->modelKeys(),
    reader: fn (User $user) => $user->id,
    load: ['sharedWith:id'],
)
```

The relations are loaded once per indexed batch, on a copy of the rows, and the keys are computed with lazy loading disabled: a relation read without `load` throws `UndeclaredSearchKeyRelationException`. When that relation changes, the documents must be indexed again: see [Keeping the keys fresh](/search/keeping-the-keys-fresh).

### The decision context

The `reader` callback may take the `AccessContext` as its second parameter, the object that the hooks of a perimeter class receive. A key that depends on the brand of the request reads it from the [decision context](/essentials/readers#the-decision-context):

```php
use Lomkit\Access\AccessContext;

->searchKeys(
    name: 'author',
    row: fn (Post $post) => [[$post->brand_id, $post->author_id]],
    reader: fn (User $user, AccessContext $context) => [[$context->decisionContext()['brand'], $user->id]],
)
```

- The ability of this context is always `view`: a search finds the rows the reader may view.
- The `row` callback never receives a context, since rows are indexed outside any request. The context part of a row key comes from a column of the row.
- A second parameter that cannot receive an `AccessContext`, or a third parameter without a default value, throws `InvalidSearchKeyReaderException`.

### Levels and unrestricted perimeters

- In a `Levels::of()` group, only the highest level the reader reaches gives its keys, as in the queries.
- An [unrestricted](/essentials/perimeters#unrestricted-perimeters) perimeter gives no key filter: the search keeps every document inside the boundary. It takes no search keys: declaring them throws `UnrestrictedPerimeterCallbackException`.
- A perimeter that applies to the reader but declares no search keys adds no row to the search, which is then narrower than the query, never wider. `php artisan access:check` reports it as `perimeter_without_search_keys`.

## The boundary

A [boundary](/essentials/boundaries) declared with `Boundary::where()` gives its search keys from the same declaration. A boundary class declares them in a `searchKeys()` method:

```php [app/Access/Boundaries/TenantBoundary.php]
use Illuminate\Database\Eloquent\Model;
use Lomkit\Access\Search\SearchKeys;

class TenantBoundary extends Boundary
{
    protected function searchKeys(): ?SearchKeys
    {
        return SearchKeys::of(
            name: 'tenant',
            row: fn (Model $row) => $row->tenant_id,
            reader: fn (User $user) => $user->tenant_id,
        );
    }

    // scope() and includes() as on the Boundaries page
}
```

- The `reader` callback of `SearchKeys::of()` may take the `AccessContext` as its second parameter too, so a boundary that reads the brand of the request finds the same rows in SQL and in a search.
- A controlled search on an engine that stores documents throws `UnsearchableBoundaryException` when the boundary class has no `searchKeys()`.
- A reader whose boundary value is `null` finds nothing.

## The documents

Each document carries two more attributes:

<table>
<thead>
  <tr>
    <th>
      Attribute
    </th>
    
    <th>
      Content
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        _access
      </code>
    </td>
    
    <td>
      the keys of the row for every perimeter that declares search keys
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        _boundary
      </code>
    </td>
    
    <td>
      the keys of the row for the boundary
    </td>
  </tr>
</tbody>
</table>

A document is found when it shares a key with the reader in `_access`, unless the reader is unrestricted, and in `_boundary`, when the control has a boundary.

The engine never receives a key as you declare it: each key leaves the application as a digest of 32 lowercase hexadecimal characters, in the documents, in the filters and in the [browser tokens](/search/from-the-browser) alike, so every engine compares it exactly (see [Engines](/search/engines#why-digests)). The keys stay readable in the application: the failures of [`assertSearchAgrees()`](/testing-and-tooling/testing#the-search) list them.

## Searching

The search of a `ControlledSearchable` model says whether it is controlled:

```php
Post::search('budget')->controlled()->paginate(25);   // the posts the signed-in user may view
Post::search('budget')->controlledFor($user)->get();   // for a named reader: jobs, listeners, commands
Post::search('budget')->uncontrolled()->paginate(25); // every post, on purpose: back office, exports
Post::search('budget')->paginate(25);                  // throws UndeclaredSearchScopeException
```

- A search that runs without `controlled()`, `controlledFor()` or `uncontrolled()` throws `UndeclaredSearchScopeException`. Declaring two of them throws `ConflictingSearchScopeException`.
- Without a signed-in user, with `controlledFor(null)`, or for a reader that no perimeter allows, a controlled search returns an empty page without calling the engine.
- A search always finds the rows the reader may **view**. `controlled()` and `controlledFor()` take no ability: one given after the reader throws `UnsearchableAbilityException`. Search, then decide the other abilities on the results with [`withAbilities()`, `Access::preload()` or `reachableKeys()`](/digging-deeper/batched-decisions).

A search callback, such as `Post::search('budget', fn ($client, $query, $options) => ...)`, receives the options that hold the access filter: pass them on to the engine, never rebuild them.

## Next steps

- Declare the two attributes in the settings of your engine: [Engines](/search/engines).
- Reindex the documents when the data their keys read changes: [Keeping the keys fresh](/search/keeping-the-keys-fresh).
- Prove that the search finds the rows of the query: [`assertSearchAgrees()`](/testing-and-tooling/testing#the-search).
