# Searching outside HTTP

> Replay a client search payload from a job, a command or an export with Rest::search(), with the validation, perimeter and policies of the endpoint.

`Rest::search()` runs the search of a resource from PHP, for a given user, as the search endpoint runs it. Use it to replay a search payload that a client built: a saved search that a scheduled job sends each morning, a console command that reruns it, or an export of what a user sees. To read rows that your own code chooses, keep using Eloquent.

```php
use Lomkit\Rest\Facades\Rest;

$search = Rest::search(TicketResource::class)
    ->as($user)
    ->payload($savedSearch);

$page = $search->page();          // LengthAwarePaginator of the models
$body = $search->render(page: 2); // the endpoint body, as an array
$rows = $search->lazy();          // every rendered row, by chunks
```

## The builder

- `payload()` takes the value of the `search` key of the endpoint body. It is validated with the rules and limits of the endpoint. A failure throws `Illuminate\Validation\ValidationException` with the keys and messages of the endpoint, such as `search.filters.0.field`. Without `payload()`, the search runs as an endpoint body without `search`.
- `as()` is required. Without it, the search throws `SearchRunException`: `The search of the resource [App\Rest\Resources\TicketResource] has no user. Call as() with the user, or as(null) to search as a guest.`
- `as(null)` searches as a guest, also when a user is logged in. `as($user, 'api')` names the guard of the user; the default guard applies otherwise.
- The given user is the one that `$this->request()->user()` returns in `perimeterQuery()`, in the declarations of the resources and in their hooks, at every include level. The policies and the decision cache use that user and guard. The logged-in user and the default guard of the application do not change.
- `viewAny` is checked before the search, as on the endpoint: a denial throws `Lomkit\Rest\Exceptions\AuthorizationDenied`.

## page() and render()

```php
use Illuminate\Support\Facades\Mail;
use Lomkit\Rest\Facades\Rest;

public function handle(): void
{
    $page = Rest::search(TicketResource::class)
        ->as($this->user)
        ->payload($this->savedSearch->payload)
        ->page();

    Mail::to($this->user)->send(new OpenTickets($page->items(), $page->total()));
}
```

- `page()` returns the `Illuminate\Contracts\Pagination\LengthAwarePaginator` of the models of the page, with their includes cut to their limits.
- `render()` returns the body of the endpoint as an array: `json_encode($body)` is the content that the endpoint answers for the same user and payload, `meta` included.
- The objects that stay `{}` when empty, such as `meta`, `pivot` and `gates`, are `stdClass` instances in that array.
- `page(page: 2)` and `render(page: 2)` read that page instead of the `page` of the payload. It is validated as `search.page`.
- `page()` and `render()` run `searching()` before the query and `searched()` after it, as on the endpoint.
- `page()` and `render()` are bounded by `rest.limits.sizes.rows`, as a page of the endpoint: `The search field takes the response over the limit of 49 rows: it can render up to 50 rows.` for a page of 50 rows with the limit set to 49. `lazy()` does not count rows. See [Response rows](/resources/limits#response-rows).
- The values of a row follow the type of their field, as on the endpoint: a `Number` value is a number, and an empty `Json` value is an object. See [Value types in rows](/resources/fields#value-types-in-rows).
- A payload that asks for [totals](/search/totals) needs `render()`, which returns them under the root `totals` key. `page()` throws `SearchRunException`: `The search of the resource [App\Rest\Resources\TicketResource] asks for totals, which page() cannot return: a paginator holds the rows only. Call render(), which returns the totals at the root of the page, or send the search without totals.`
- A payload with `"source": "engine"` runs on the search engine of a resource that [serves its lists](/search/search-engines#engine-lists), and gives `The search.source field is prohibited.` elsewhere.

## lazy() and exports

`lazy()` reads every row of the search. Here, an export of the tickets that the user sees, with the filters of the client, streamed in the request:

```php [app/Http/Controllers/TicketExportController.php]
use Illuminate\Http\Request;
use Lomkit\Rest\Facades\Rest;
use Symfony\Component\HttpFoundation\StreamedResponse;

public function __invoke(Request $request): StreamedResponse
{
    $rows = Rest::search(TicketResource::class)
        ->as($request->user())
        ->payload($request->input('search', []))
        ->lazy();

    return response()->streamDownload(function () use ($rows): void {
        $file = fopen('php://output', 'w');

        foreach ($rows as $row) {
            fputcsv($file, [$row['id'], $row['title'], $row['status']]);
        }

        fclose($file);
    }, 'tickets.csv');
}
```

```json [POST /tickets/export]
{
  "search": {
    "filters": [{"field": "status", "value": "open"}],
    "selects": [{"field": "id"}, {"field": "title"}, {"field": "status"}],
    "sorts": [{"field": "id"}]
  }
}
```

- `lazy(chunk: 500, max: null)` returns an `Illuminate\Support\LazyCollection` of rendered rows. Each row is the row that the endpoint returns in `data`: its fields, its includes cut to their limits with `@more`, and the `gates` that the payload asks for.
- In order, `lazy()` returns the rows of every page of the endpoint, each row once.
- When `lazy()` is called, it validates the payload, checks `viewAny`, runs `searching()` and reads the keys of the rows in the order of the search. A validation error or a denial throws there, before the streamed response starts.
- The rows load and render by chunks of `chunk` keys while you iterate, with their includes and aggregates. The query of the keys selects the model key only, so only the keys of all rows stay in memory.
- A row deleted after its key was read is skipped. Each iteration loads the rows again.
- `max` reads the first `max` rows only. `lazy()` ignores the `limit` and the `page` of the payload.
- `searched()` does not run, and an override of `paginate()` in the resource does not apply to `lazy()`.

<tip>

To export many rows in the background, in the columns that the client picks, use a queued, batched action whose jobs each write a chunk of rows, and let the client download the file. See [Exports](/actions-and-metrics/exports).

</tip>

### Searches on a search engine

`lazy()` also reads a search that runs on a [search engine](/search/search-engines): a text search on a `ScoutEngine` resource, and `"source": "engine"` on a resource that [serves its lists](/search/search-engines#engine-lists). `source` keeps the 422 of `page()` on the other resources, and `"source": "database"` streams in SQL.

- When `lazy()` is called, it reads every key of the search from the engine, whatever `chunk`: in one page on the Scout `collection`, `database` and `null` drivers, and elsewhere in pages of the largest size that the engine takes, 250 on Typesense and 1,000 on Meilisearch, Algolia, Turbopuffer and the profiles that extensions provide.
- While you iterate, the rows load by chunks of `chunk` keys, in the order of the engine, each once, as the rows of an engine page: with the global scopes of the model and `search.trashed`, without `perimeterQuery()` and without the `RestrictsQueries` restrictions of the extensions. `lazy()` returns the rows that the pages of the endpoint show, through `ScoutEngine::perimeter()` and the engine restrictions, which apply when the keys are read.
- A row whose key was read and that leaves the perimeter during a long stream is still streamed, as a page loaded before the change would show it. A row deleted since indexing is skipped.
- Only the keys stay in memory, as in SQL, and `max` caps the keys read from the engine.

Every refusal throws when `lazy()` is called, before a streamed response starts. Both exceptions below extend `SearchRunException`, so a `catch (SearchRunException)` keeps catching them. Catch them apart to answer each one:

```php
try {
    $rows = $search->lazy();
} catch (EngineResultsChangedException) {
    $rows = $search->lazy();
} catch (EngineWindowException $e) {
    // narrow the search, or lazy(max: $e->window ?? 1000)
}
```

- `Lomkit\Rest\Exceptions\EngineWindowException` when the search can match more results than the engine returns, and `max` does not fit within that bound: the result window (10,000 on Turbopuffer) or the reach that the engine reports (`pagination.maxTotalHits` on Meilisearch, `paginationLimitedTo` on Algolia). It is also thrown when the engine does not report its reach, because the key of the application cannot read the settings of the index, and `lazy()` has no `max`. Its `window` holds the bound that refused the search, `null` when the engine reports none.
- `Lomkit\Rest\Exceptions\EngineResultsChangedException` when a key comes back twice or the total changes while the keys are read: call `lazy()` again, and set `scout.after_commit` to `true` so that the index changes once the transactions commit.
- On Turbopuffer, whose total does not count the text, the keys are read until a page is not full: a row that moves from one page to another while they are read cannot be detected there. The window still bounds the walk: when the keys read reach its 10,000 results and `max` is absent or above it, `lazy()` throws `EngineWindowException`.

### lazy() errors

All of them throw `Lomkit\Rest\Exceptions\SearchRunException` or one of its subclasses:

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

<tbody>
  <tr>
    <td>
      The search can match more results than the engine returns
    </td>
    
    <td>
      <code>
        The search of the resource [App\Rest\Resources\TicketResource] runs on a search engine, which returns at most its first 10000 results, and the search can match more. Give lazy() a max of at most 10000, narrow the search, or read the pages with page().
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      The engine does not report its reach, and <code>
        lazy()
      </code>
      
       has no <code>
        max
      </code>
    </td>
    
    <td>
      <code>
        The search of the resource [App\Rest\Resources\TicketResource] runs on a search engine that does not report how many results it can return. lazy() reads every row: give lazy() a max, or read the pages with page().
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      The results changed while the keys were read
    </td>
    
    <td>
      <code>
        The search engine results of the resource [App\Rest\Resources\TicketResource] changed while lazy() read their keys. Call lazy() again, and set scout.after_commit to true so that the index changes once the database transactions commit.
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      A <code>
        chunk
      </code>
      
       below 1
    </td>
    
    <td>
      <code>
        The chunk of lazy() must be at least 1, [0] given.
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      A negative <code>
        max
      </code>
    </td>
    
    <td>
      <code>
        The max of lazy() must be at least 0, [-1] given.
      </code>
    </td>
  </tr>
</tbody>
</table>

`lazy()` refuses `totals` with a `ValidationException`: `The search.totals field is prohibited.` See [Totals](/search/totals#outside-http).
