Search

Engines

Declare the access attributes in Meilisearch, Typesense, Algolia or Turbopuffer, use the database engine, and combine your own filters with the access filter.

Index settings

Declare _access and _boundary as filterable in the settings of each searchable model. Access::searchFilterables() returns ['_access', '_boundary']:

// config/scout.php
'meilisearch' => [
    'index-settings' => [
        Post::class => [
            'filterableAttributes' => [...Access::searchFilterables(), 'status'],
        ],
    ],
],

Then push the settings and index the documents:

php artisan scout:sync-index-settings
php artisan scout:import "App\Models\Post"

Turbopuffer sets the type of an attribute on its first write and cannot change it: declare the schema before the first write, or delete the namespace (scout:flush) and import it again.

Why digests

Each key leaves the application as a digest of 32 lowercase hexadecimal characters. Search engines do not compare indexed strings verbatim: Typesense drops symbols such as . and _ and cuts values at 100 characters, so author.1.23 would match author.12.3, and Meilisearch cuts a stored value at 468 bytes. A digest has a fixed length and no symbol, so every engine compares it exactly, and the engines need no setting for it: no symbols_to_index or token_separators on Typesense.

Supported engines

EngineControlled search
Algolia, Meilisearch, TypesenseFiltered with whereIn on _access and _boundary
TurbopufferFiltered with its native ContainsAny operator
databaseThe control's SQL inside the search query, without keys
nullAccepted: it finds nothing
collectionRefused: it paginates before it filters
Any other engineRefused, unless you trust it

The package checks the engines with instanceof, so a subclass of a supported engine is trusted as it is.

A subclass keeps the duties of a trusted engine: it sends the options it receives, the access filter included, on every read path, as ...$options does in the multi-search engine below. The package does not check what a subclass overrides.

The database engine

The database engine searches with SQL: a controlled search applies the control's SQL inside the search query, through Scout's query() callback, which still runs the callback you pass to query(). No keys are computed for it. It is also the engine for your tests: the collection engine throws UnsupportedSearchEngineException on a controlled search.

Trusting another engine

Any other engine throws UnsupportedSearchEngineException: an engine that ignored whereIn would return every document. When your engine filters correctly, trust it in the boot() method of a service provider:

Access::trustSearchEngine(ElasticsearchEngine::class);

A trusted engine must:

  • render whereIn on an array attribute as "at least one element in common", and AND the fields together, _boundary with _access;
  • compare each value as a whole string;
  • apply the whereIns of the search on every read path: get(), paginate(), simplePaginate(), keys(), raw() and cursor();
  • write scoutMetadata() with each document, as the Meilisearch and Typesense engines do, or no key is indexed;
  • for laravel-rest-api, have an engine profile that implements MatchesStringLists, or its searches throw UnsupportedRestSearchException.

It needs nothing for a reader who reaches nothing: the package never calls the engine for them.

Your own filters

Your where() and whereIn() clauses narrow a controlled search on every engine. Filters passed through options() behave differently on each engine:

  • Typesense. A filter_by from options() or typesenseSearchParameters() is combined with the access filter as (<your filter_by>) && (<access filter>), on every read path and in a search callback, so it can only narrow the results. Your filter must end on its own: a filter that is not a string, or that leaves a backtick-quoted value, a geo filter, a reference or an object filter open, throws UncombinableSearchFilterException.
  • Meilisearch and Algolia. Scout sends its own filter, built from the where() and whereIn() clauses and the access filter, in place of the filter (Meilisearch) or filters (Algolia) of options(). Put your conditions in where() and whereIn(). Algolia still ANDs the facetFilters and numericFilters of options().
  • Turbopuffer. The access filter is added to the native filters of options['filters'], joined with And, and applied again when the search runs, so a later options() or whereIn() cannot remove it.

Some engine features would show documents that the filter does not keep, so a controlled search turns them off:

  • Typesense: filter_curated_hits is always true, so pinned hits and curated documents go through the filter. Natural-language search (nl_query) throws NaturalLanguageSearchException; do not use a preset that turns it on for a controlled model.
  • Algolia: enableRules and enableABTest are always false, since a rule can promote records whatever the filters and an A/B test can answer from another index.

An unrestricted reader without a boundary has no access filter: their search is sent as you wrote it, with these features on.

Readers with many keys

A reader with many keys sends a long filter. Scout's Typesense engine searches with a GET request, and Typesense refuses a query string longer than 4,000 encoded characters with HTTP 400: the search fails, it never shows a row too many. Each key costs about 36 encoded characters, so a search holds about 100 keys, _boundary and _access together. The keys through a parent multiply.

When your readers hold more, search through Typesense's multi_search endpoint, which takes the filter in a POST body, with a subclass of Scout's engine registered under the typesense driver. It needs Scout 11.7 or later:

use Laravel\Scout\Builder;
use Laravel\Scout\EngineManager;
use Laravel\Scout\Engines\TypesenseEngine;
use Typesense\Client;
use Typesense\Documents;

class MultiSearchTypesenseEngine extends TypesenseEngine
{
    protected function executeSearch(Builder $builder, Documents $documents, array $options): mixed
    {
        $results = $this->typesense->getMultiSearch()->perform([
            'searches' => [[...$options, 'collection' => $builder->index ?? $builder->model->searchableAs()]],
        ]);

        $result = $results['results'][0] ?? [];

        if (isset($result['error'])) {
            throw $this->marshalMultiSearchException($result);
        }

        return $result;
    }
}

// In the boot() method of a service provider
resolve(EngineManager::class)->extend('typesense', fn () => new MultiSearchTypesenseEngine(
    new Client(config('scout.typesense.client-settings')),
    config('scout.typesense.max_total_results', 1000),
    config('scout.typesense'),
));

The subclass is trusted without Access::trustSearchEngine(), since it passes the options it receives, the access filter included, to the engine. Its browser tokens keep working, and it covers the searches of laravel-rest-api too. Algolia accepts at most 1,000 filters in a query, so a reader with more keys than that cannot search an Algolia index.

The engine is the only barrier

A controlled search shows what the index says. An index that lags behind can show a row that just left the reader's perimeters until the row is indexed again, and documents keep the keys of a former rule until they are reindexed. Keeping the keys fresh covers what reindexes them.