Why we wrote it
Many Laravel applications already run on PostgreSQL, and sooner or later most of them need a search box that is better than LIKE '%term%'. The usual answer is a separate search server. This package is our answer for the cases where that is more infrastructure than the problem deserves: a Laravel Scout engine that keeps the whole index in one PostgreSQL table, search_documents, next to the data it describes. Your code still says Product::search('yoga mat'), so moving to another engine later is a SCOUT_DRIVER change, not a rewrite. Why we build on Laravel at all is a separate topic, covered in our article on Laravel for business applications.
What "hybrid" means here
Every query runs up to three independent rankings over that table.
- Weighted full-text search. A database trigger builds a
tsvector with the title at weight A and the body at weight D, so a hit in a product name outranks one buried in a long description. The query is parsed with websearch_to_tsquery and ranked with ts_rank_cd.
- Trigram word similarity.
pg_trgm compares the query with a short, lowercased, unaccented field built from the title (or a SKU, or a name). This is what tolerates typos and missing diacritics.
- Semantic similarity. Cosine distance over
pgvector embeddings, which runs only once you plug in an embedding provider of your own.
The three lists are not glued together. Each branch fetches four times the requested number of candidates and numbers its hits; a hit then scores weight / (k + rank) in every branch where it appears, and those scores are summed. This is reciprocal rank fusion, with k = 60 by default. It is what makes the combination meaningful at all: ts_rank_cd, word_similarity and cosine similarity live on different scales, so adding raw scores would mean nothing, while positions in a ranking are comparable. The effect is that a document ranking moderately well in all three lists beats one that tops a single list.
The trigram branch is not decoration. Polish shows why: PostgreSQL ships no Polish stemmer at all, so the default configuration maps pl to simple, which does no stemming. Trigrams relate joga and jogi because they share letters, not because they understand Polish grammar, and that is enough to find inflected words.
Why inside the database you already run
A separate search server is another service to deploy, secure, monitor and back up, and another copy of your data to keep in sync. Here the index is a table. It is backed up with everything else, filters are jsonb containment tests applied inside each branch rather than after the LIMIT, and in a multi-tenant application the tenant is a real column with a real predicate, repeated in every branch. For catalogues, content sites and internal tools of modest size, keeping search where the data already lives can be the better trade: fewer moving parts, and one database to reason about.
Decisions you can see in the code
- One model, many documents. Instead of Scout's
toSearchableArray(), a model returns one document per locale from toSearchDocuments(). Returning an empty array means "delete every row for this model", so unpublishing and deleting end in the same state.
- Embeddings are never on the save path. Calling an embedding API is a paid, rate-limited network round-trip. The indexer clears the vector whenever the text changes, and a separate backfill fills it in. A provider outage therefore never blocks a model save.
- An exact vector scan, on purpose. There is no approximate (HNSW or IVFFlat) index on the embedding column, because pgvector filters the approximate candidate set after the fact, and a query narrowed to one tenant and one type could come back short or empty while matches exist.
- Refuse rather than guess. An unresolvable tenant throws instead of widening the query or returning nothing.
whereNotIn(), within() and strict > or < comparisons throw instead of being silently ignored. A platform-wide read has to be asked for by name.
We package our other Laravel work in the same spirit; Laravel Cookie Consent is another of our open-source packages.
The honest limits
The package is at version 1.1.1. Its test suite runs against real PostgreSQL 17 with pgvector on every supported PHP and Laravel version, in both tenancy modes, but it has not yet been proven by a production adopter. The semantic branch is an exact scan over every embedded row in the tenant and type you query, so its cost grows with that slice of the corpus. Paginated Scout results are capped at 500 hits.
A dedicated engine such as Meilisearch, Typesense, Algolia or Elasticsearch gives you things this package does not have: facet counts, result highlighting, geographic search, and a search tier that scales separately from your primary database.
- Your application does not use PostgreSQL, or you cannot get the
vector, pg_trgm and unaccent extensions installed.
- Your models use UUID or ULID keys.
- Search traffic is heavy enough that it should not share resources with your main database.
- You need any of those features, or an approximate vector index over a very large corpus.
Installation and usage guide
Requirements
- PHP 8.3 or newer (
"php": "^8.3")
- Laravel 12 or 13 (
illuminate/support, illuminate/database and illuminate/contracts ^12.0|^13.0)
- Laravel Scout 11 (
laravel/scout ^11.0)
- PostgreSQL 14 or newer, with the
vector, pg_trgm and unaccent extensions installable
There is no pgvector/pgvector PHP dependency: the migration uses Laravel's native $table->vector(...) column type. Useful references: the Laravel Scout documentation, PostgreSQL's full-text search chapter and pg_trgm, and pgvector.
Installation
- Install the package. The service provider is registered automatically through package discovery.
composer require core45/laravel-scout-postgres-hybrid
- Publish the configuration file and the schema migration.
php artisan vendor:publish --tag=scout-postgres-config
php artisan vendor:publish --tag=scout-postgres-migrations
- Enable the PostgreSQL extensions (next section).
- Set
SEARCH_EMBEDDING_DIMENSIONS if you plan to use embeddings whose width is not 1536. The column is a typed vector(N), so this must be right before you migrate.
- Run
php artisan migrate.
- Point Scout at the driver, in
config/scout.php or in .env:
SCOUT_DRIVER=postgres
A typical .env for a fresh install:
SCOUT_DRIVER=postgres
# Single-tenant is the default; use "column" for multi-tenant
SCOUT_POSTGRES_SCOPE_MODE=none
# Must match your embedding model's width, set BEFORE migrating
SEARCH_EMBEDDING_DIMENSIONS=1536
# Queue for the index sync job
SEARCH_QUEUE=search
Enabling the PostgreSQL extensions
CREATE EXTENSION needs superuser privileges, so on managed PostgreSQL (RDS, Cloud SQL, Supabase) an ordinary application role usually cannot run it. That is why the extensions migration is published separately.
If your database role can create extensions, publish and run the extensions migration as well:
php artisan vendor:publish --tag=scout-postgres-extensions-migration
php artisan migrate
If it cannot, ask a superuser to run these statements once, and publish only the schema migration:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE EXTENSION IF NOT EXISTS unaccent;
If the extensions migration fails for lack of privileges, it stops with a message telling you which statement a superuser needs to run. Its down() deliberately does not drop the extensions, because other parts of your schema may depend on them.
What the migration creates
The schema migration creates the search_documents table: one row per model and locale, with searchable_type, searchable_id, locale, text_search_config, title, body, trigram_text, content_hash, filters (jsonb), embedding (vector(N), nullable), embedding_fingerprint, timestamps, and the tenant column when scope.mode is column. It also creates:
- an immutable
f_unaccent(text) wrapper, so unaccenting can be used in an index;
- a
search_vector tsvector column, maintained by the search_documents_vector_update trigger (title weight A, body weight D);
- GIN indexes on
search_vector, on trigram_text (gin_trgm_ops) and on filters;
- a unique index on
(searchable_type, searchable_id, locale) and a lookup index named search_documents_lookup_idx.
There is no approximate index on embedding, by design (see above). On a connection that is not PostgreSQL both migrations do nothing, so a test suite running on SQLite still migrates; the engine then returns empty results and writes nothing.
Configuration
Everything lives in config/scout-postgres.php.
| Key | Default (env) | Meaning |
scope.mode | 'none' (SCOUT_POSTGRES_SCOPE_MODE) | 'none' for single-tenant, 'column' for multi-tenant. Anything else throws. |
scope.column | 'tenant_id' | Tenant column. Must be a lowercase, unquoted identifier and not a reserved SQL keyword. |
scope.table | 'tenants' | Table the foreign key references. |
scope.foreign_key | true | Whether to create a foreign key on the tenant column. |
scope.on_delete | 'cascade' | cascade, restrict, set null or no action. set null requires nullable. |
scope.nullable | false | Whether the tenant column is nullable. |
hydration.strip_global_scopes | [] | Names of your global scopes to remove when loading result models, when the sync job reloads a model and when looking for orphans. scout-postgres:reindex does not strip them. |
types | [] | Your DocumentType classes. Nothing is indexed until one is registered. |
cache.prefix | 'scout-postgres' (SCOUT_POSTGRES_CACHE_PREFIX) | Prefix for cached query embeddings, so two applications can share a cache store. |
text_search.default | 'simple' (SEARCH_TEXT_CONFIG_DEFAULT) | PostgreSQL text search configuration for locales not in the map. |
text_search.configs | de, en, es, fr, it, pl | Locale to regconfig map: german, english, spanish, french, italian, and simple for Polish. |
trigram.word_similarity_threshold | 0.4 (SEARCH_TRIGRAM_THRESHOLD) | Minimum word_similarity for a trigram match, set per query with set_config. |
synonyms | [] | Query expansion pairs. Ships empty. |
hybrid.k | 60 (SEARCH_RRF_K) | The RRF constant. Higher values flatten the advantage of top-ranked hits. |
hybrid.weights.keyword | 1.0 (SEARCH_WEIGHT_KEYWORD) | Weight of the full-text and the trigram branch in the fusion. |
hybrid.weights.semantic | 1.0 (SEARCH_WEIGHT_SEMANTIC) | Weight of the semantic branch in the fusion. |
vector.enabled | true (SEARCH_VECTOR_ENABLED) | When false, queries are not embedded and the semantic branch does not run. The backfill is not affected: it runs whenever the provider's isReady() is true. |
vector.dimensions | 1536 (SEARCH_EMBEDDING_DIMENSIONS) | Width of the vector(N) column, read by the migration. |
vector.min_similarity | 0.4 (SEARCH_MIN_SIMILARITY) | Minimum cosine similarity for a semantic hit. |
vector.query_cache_ttl | 3600 (SEARCH_QUERY_VECTOR_TTL) | Seconds a query embedding stays cached. |
vector.unavailable_ttl | 60 (SEARCH_VECTOR_UNAVAILABLE_TTL) | Seconds a failed embedding call is remembered, so an outage costs one attempt per interval rather than one per search. |
max_body_length | 100000 (SEARCH_MAX_BODY_LENGTH) | Body is truncated to this many characters. 0 disables truncation (not recommended). |
queue | 'default' (SEARCH_QUEUE) | Queue for the index sync job. |
Step 1: describe your document types
The package does not know what your application indexes, so you tell it by implementing Core45\ScoutPostgres\Contracts\DocumentType. A backed enum is the natural shape:
namespace App\Enums;
use App\Models\Post;
use App\Models\Product;
use Core45\ScoutPostgres\Contracts\DocumentType;
enum SearchableType: string implements DocumentType
{
case Product = 'product';
case Post = 'post';
public function value(): string
{
return $this->value;
}
public function modelClass(): string
{
return match ($this) {
self::Product => Product::class,
self::Post => Post::class,
};
}
public function isTranslatable(): bool
{
return $this === self::Product; // posts are indexed once, under '*'
}
}
Register it:
// config/scout-postgres.php
'types' => [App\Enums\SearchableType::class],
value() is stored in searchable_type (at most 64 characters) and is the join key when results are loaded, so it must stay stable across deploys: renaming it orphans every indexed row of that type. isTranslatable() decides whether the type has one row per locale (true) or one row per model under DocumentType::LOCALE_ANY, which is '*' (false). A backed enum is expanded through ::cases(); any other class is constructed with no arguments. Compare types by value(), never with ===.
Step 2: make your models indexable
Implement Core45\ScoutPostgres\Contracts\SearchIndexable and use the SearchableWithoutSyncing trait:
namespace App\Models;
use App\Enums\SearchableType;
use Core45\ScoutPostgres\Concerns\SearchableWithoutSyncing;
use Core45\ScoutPostgres\Contracts\SearchIndexable;
use Core45\ScoutPostgres\DTOs\SearchDocumentData;
use Illuminate\Database\Eloquent\Model;
class Product extends Model implements SearchIndexable
{
use SearchableWithoutSyncing;
public function toSearchDocuments(): array
{
if (! $this->is_published) {
return []; // no documents means "delete this model's rows"
}
return collect(['en', 'pl'])->map(fn (string $locale) => SearchDocumentData::make(
searchableType: SearchableType::Product,
searchableId: (int) $this->getKey(),
locale: $locale,
title: $this->translateOrDefault($locale)->name,
body: $this->translateOrDefault($locale)->description ?? '',
trigramSource: $this->translateOrDefault($locale)->name.' '.$this->sku,
filters: [
'brand_id' => $this->brand_id,
'in_stock' => $this->in_stock,
'size' => $this->size,
'price' => $this->price,
],
))->all();
}
}
What to know about SearchDocumentData::make():
- Its parameters are
searchableType, searchableId, locale, title, body (default ''), trigramSource (default: the title) and filters (default []).
- Resolve each locale's text the way your pages actually render it, fallbacks included. A product that only has a Polish name should stay findable on the English site by that name, just as it is browsable there.
trigramSource should be short, identifier-like text: a title, a SKU, a name. Never the body, because word similarity against a long description cannot reach the threshold.
- HTML tags in title and body are replaced by spaces and whitespace is collapsed, so rich-text descriptions do not merge words.
filters is stored as jsonb. Only the keys you put here can be used in where() and whereIn().
- Two documents for the same locale, or a document whose type or id does not match the model, throw
InvalidArgumentException.
For a type that is not translatable, index one document under the wildcard locale:
use Core45\ScoutPostgres\Contracts\DocumentType;
// For a type whose isTranslatable() returns false: one row per model
SearchDocumentData::make(
searchableType: SearchableType::Post,
searchableId: (int) $this->getKey(),
locale: DocumentType::LOCALE_ANY, // '*'
title: $this->title,
body: $this->body ?? '',
);
SearchableWithoutSyncing gives you Scout's query side (Model::search(), searchable(), unsearchable()) without Scout's model observer. Scout's observer only sees a model's own save, which is less than a denormalised index needs. Because of that, withoutSyncingToSearch() is a no-op on these models; to suppress indexing use SearchIndexer::withoutIndexing() (below).
Step 3: keep the index current
Register the package's observer for each indexable model:
// app/Providers/AppServiceProvider.php
use App\Models\Post;
use App\Models\Product;
use Core45\ScoutPostgres\Observers\SearchDocumentObserver;
public function boot(): void
{
Product::observe(SearchDocumentObserver::class);
Post::observe(SearchDocumentObserver::class);
}
On saved, deleted and restored it dispatches Core45\ScoutPostgres\Jobs\SyncSearchDocumentJob after the database transaction commits, onto the queue named by SEARCH_QUEUE. The job is unique per tenant, type and id until it is processed, is tried 3 times with backoffs of 10, 30 and 60 seconds, and has a 120-second timeout. Because index work can fan out to one row per locale, it is worth running it on its own queue, away from user-facing jobs. Remember to run a queue worker for that queue.
When a contributor changes rather than the model itself (a renamed brand that appears in every product's text, a pivot sync() that fires no Eloquent event), dispatch a reconcile yourself. Which models contribute to which documents is your application's knowledge, so the package gives you the primitive:
use App\Enums\SearchableType;
use Core45\ScoutPostgres\Search\SearchIndexer;
// $scope is your tenant key, or null when scope.mode is 'none'
app(SearchIndexer::class)->reconcile($scope, SearchableType::Product, $productId);
To suppress indexing during a bulk import, wrap it, then reindex once:
use Core45\ScoutPostgres\Search\SearchIndexer;
SearchIndexer::withoutIndexing(fn () => $importer->run());
Step 4: index and reindex
The package's own command rebuilds search_documents from your models. It reconciles rather than inserting, so running it twice, or after a configuration change, is safe and is the supported way to restate the index.
php artisan scout-postgres:reindex # single-tenant
php artisan scout-postgres:reindex --scope=1 --prune # multi-tenant, also prune orphans
php artisan scout-postgres:reindex --scope=1 --scope=2 --type=product
php artisan scout-postgres:reindex --no-embeddings # skip the embedding pass
| Option | Meaning |
--scope=* | Tenant keys to reindex. Required in column mode, rejected in none mode. Only integer keys are accepted. |
--type=* | Limit to these DocumentType values. Defaults to every registered type. |
--prune | Also delete documents whose source row no longer exists. |
--no-embeddings | Skip the embedding backfill that otherwise runs after each scope. |
--embed-limit=1000 | Documents embedded per scope in one run. |
--chunk=200 | Source models loaded per batch (with chunkById). |
In multi-tenant mode the command refuses to run without --scope, because the package cannot list your tenants and will not guess "all of them". Scout's own commands also work: scout:import reconciles each model through the same indexer, and scout:flush deletes one type's documents within the tenant returned by ScopeResolver::current(), so in a console command with no current tenant it throws; call SearchIndexer::purgeType($scope, $type) or purgeScope($scope) instead.
php artisan scout:import "App\Models\Product"
Scout's createIndex() and deleteIndex() throw a LogicException: there are no named indexes, only one table with a tenant column.
Step 5: search
Product::search('yoga mat')->get(); // at most 20 hits unless you set a limit
Product::search('yoga mat')->take(50)->get();
Product::search('yoga mat')->paginate(20);
Product::search('yoga mat')->options(['locale' => 'pl'])->get();
Product::search('yoga mat')->options(['scope' => $tenant->id])->paginate(20);
How the Scout builder maps onto the engine:
- Without
take(), get() returns at most 20 hits.
- The locale is
options(['locale' => ...]) if you pass one, otherwise app()->getLocale(). Non-translatable types always search the '*' locale.
paginate() and simplePaginate() search once, up to 500 hits, and let Eloquent paginate the loaded models in relevance order. Results beyond 500 cannot be reached by paging.
orderBy() is applied after relevance, as a tie-breaker. To discard relevance order, call reorder() inside a query() callback.
- An empty search term runs no full-text or trigram branch.
Filters compile to conditions on the filters column inside every branch, so they narrow the search rather than discarding top-ranked hits afterwards:
Product::search('yoga mat')->where('brand_id', 7)->get();
Product::search('yoga mat')->whereIn('size', ['M', 'L'])->get();
Product::search('yoga mat')->where('price', '>=', 100)->where('price', '<=', 300)->get();
// Eager loading and extra constraints on the hydrated models
Product::search('yoga mat')->query(fn ($query) => $query->with('brand'))->get();
where('key', $value) becomes jsonb containment (filters @> ...), served by the GIN index.
whereIn() becomes containment tests joined with OR.
where('key', '>=', $n) and '<=' become numeric bounds. They are not index-served, and a non-numeric stored value simply falls outside the range.
whereNotIn(), any other operator (including strict > and <) and within() throw a LogicException.
- Filtering on the tenant column through
where() cannot cross tenants: it is a jsonb key test, not the real column.
Calling the branches directly
The Scout engine uses PostgresSearchService internally; you can use it yourself, for example to run one branch or to search several types at once:
use App\Enums\SearchableType;
use Core45\ScoutPostgres\DTOs\SearchQuery;
use Core45\ScoutPostgres\Search\PostgresSearchService;
$service = PostgresSearchService::for($tenant->id); // null when single-tenant
$query = SearchQuery::make(
term: 'yoga mat',
locale: 'en',
types: [SearchableType::Product],
limit: 20,
filters: ['in_stock' => true],
anyFilters: ['size' => ['M', 'L']],
rangeFilters: ['price' => ['min' => 100, 'max' => 300]],
);
$results = $service->search($query); // all three branches, RRF-fused
$results = $service->keyword($query); // tsvector only
$results = $service->trigram($query); // pg_trgm only
$results = $service->semantic($query); // pgvector only
foreach ($results as $hit) {
$hit->searchableId; // source model key
$hit->score; // fused or single-branch score
$hit->sources; // e.g. ['keyword', 'trigram']
}
$models = $service->hydrate($results, SearchableType::Product);
SearchQuery::make() requires at least one type and throws InvalidArgumentException for an empty list: there is deliberately no "search everything" default, so which content a caller may see is always written down. PostgresSearchService::for() throws UnresolvableScope if you pass null in multi-tenant mode. hydrate() returns the models in result order; hydrateQuery() returns the same as an Eloquent builder.
Tuning the hybrid ranking
Each branch contributes weight / (k + rank) for every hit it returns, and the contributions are summed. The keyword weight applies to both the full-text and the trigram branch; the semantic weight applies to the semantic branch:
SEARCH_RRF_K=60
SEARCH_WEIGHT_KEYWORD=1.0 # applied to the keyword and the trigram branch
SEARCH_WEIGHT_SEMANTIC=1.0 # applied to the semantic branch
Raise SEARCH_WEIGHT_SEMANTIC to favour meaning over wording, lower it to favour exact terms. SEARCH_TRIGRAM_THRESHOLD controls how fuzzy the trigram branch is, and SEARCH_MIN_SIMILARITY how close a vector must be to count. Each hit's sources shows which branches found it, which helps when tuning.
Languages and text search configuration
Each locale maps to a PostgreSQL text search configuration (regconfig) that chooses the stemmer. Locales missing from the map use default, and so do non-translatable types:
// config/scout-postgres.php
'text_search' => [
'default' => env('SEARCH_TEXT_CONFIG_DEFAULT', 'simple'),
'configs' => [
'de' => 'german',
'en' => 'english',
'es' => 'spanish',
'fr' => 'french',
'it' => 'italian',
'pl' => 'simple', // no Polish stemmer exists in PostgreSQL
'pt' => 'portuguese', // added: any regconfig listed by pg_ts_config
],
],
To see which configurations your server has:
SELECT cfgname FROM pg_ts_config;
The resolved configuration is copied into each row's text_search_config when it is indexed, so changing this map does not restem anything already indexed. After a change, run a full scout-postgres:reindex; a query built with one configuration against vectors built with another returns nothing. For languages without a stemmer, such as Polish, the trigram branch does the work of relating word forms.
Synonyms are applied as query expansion before the full-text and trigram queries are built, up to eight variants per query. They ship empty, because cross-language pairs such as health and zdrowie are specific to your content. Add entries only where trigrams are not enough:
// config/scout-postgres.php
'synonyms' => [
'yoga' => ['joga', 'jogi'],
'health' => ['zdrowie'],
],
Semantic search and embeddings
The semantic branch is off until you bind an EmbeddingProvider. The default binding, NullEmbeddingProvider, returns null from embed() and false from isReady(), so out of the box the package is a two-branch hybrid with no embedding infrastructure. The package has no embedding vendor dependency; you write the provider. This example uses the openai-php/laravel client:
namespace App\Search;
use Core45\ScoutPostgres\Contracts\EmbeddingProvider;
use OpenAI\Laravel\Facades\OpenAI;
class OpenAiEmbeddings implements EmbeddingProvider
{
public function embed(string $text): ?array
{
return OpenAI::embeddings()
->create(['model' => 'text-embedding-3-small', 'input' => $text])
->embeddings[0]->embedding ?? null;
}
public function isReady(): bool
{
return config('services.openai.key') !== null;
}
public function fingerprint(): string
{
return 'openai:text-embedding-3-small';
}
}
Bind it in a service provider:
// app/Providers/AppServiceProvider.php
use App\Search\OpenAiEmbeddings;
use Core45\ScoutPostgres\Contracts\EmbeddingProvider;
public function register(): void
{
$this->app->singleton(EmbeddingProvider::class, OpenAiEmbeddings::class);
}
The contract has three methods:
embed(string $text): ?array returns a list of floats, or null when no vector can be produced. Return null rather than throwing, and also return null for a vector of the wrong width.
isReady(): bool is checked before embedding, so an unconfigured provider costs no API call.
fingerprint(): string identifies the provider and the model, and must change whenever the model does.
Vectors are written by a backfill, not by the indexer. When a document's text changes (its content_hash, a SHA-256 of title and body, differs), the indexer sets its embedding to NULL; unchanged text keeps its vector, so a reindex costs no embedding calls. The backfill then embeds documents whose embedding is missing or whose fingerprint differs from the current provider, and reuses one vector for identical text within a run. scout-postgres:reindex runs it after reindexing each scope; you can also call it yourself, for example from a scheduled or queued job after your sync jobs:
use Core45\ScoutPostgres\Embedding\EmbeddingBackfill;
// Returns the number of documents embedded in this run
$embedded = app(EmbeddingBackfill::class)->run($scope, limit: 1000);
Each run embeds at most limit documents (for the command, --embed-limit, 1000 per scope by default), so a large corpus needs several runs. Running the backfill on a schedule keeps it caught up.
Until something runs the backfill, the semantic branch has no data. A document whose stored embedding_fingerprint does not match the current provider is excluded from semantic results, not merely ranked lower, so after switching models semantic recall drops until the backfill has re-embedded the corpus. Plan that run around the switch.
Query embeddings are cached for SEARCH_QUERY_VECTOR_TTL seconds under a key that includes the cache prefix, the tenant and the fingerprint. If the provider returns null, that failure is cached for SEARCH_VECTOR_UNAVAILABLE_TTL seconds and searches continue on the full-text and trigram branches.
Single-tenant and multi-tenant mode
One migration produces both schemas, driven by the scope array:
// config/scout-postgres.php
'scope' => [
'mode' => env('SCOUT_POSTGRES_SCOPE_MODE', 'none'), // 'none' or 'column'
'column' => 'tenant_id',
'table' => 'tenants',
'foreign_key' => true,
'on_delete' => 'cascade', // cascade, restrict, set null, no action
'nullable' => false,
],
Choose the mode before you migrate: the table is built for one mode, and the same ScopeDefinition object is read by the migration and by every query. A mistyped mode, a column mode without a column, an uppercase or reserved column name, or set null on a non-nullable column throws when the configuration is first resolved. In single-tenant mode, skip the rest of this section.
In multi-tenant mode, implement and bind ScopeResolver (which tenant is current, and how to turn a value into a tenant key) and ScopeRepository (whether a tenant still exists). The package ships no default for either, so forgetting them throws instead of guessing:
namespace App\Search;
use App\Models\Tenant;
use Core45\ScoutPostgres\Contracts\ScopeRepository;
use Core45\ScoutPostgres\Contracts\ScopeResolver;
use Core45\ScoutPostgres\Exceptions\UnresolvableScope;
class TenantScope implements ScopeResolver, ScopeRepository
{
public function current(): int
{
return Tenant::current()?->id
?? throw UnresolvableScope::noAmbientScope();
}
public function normalize(mixed $scope): int
{
if ($scope instanceof Tenant) {
return (int) $scope->getKey();
}
// Validate, never cast: (int) '1-not-authorized' is 1
if (is_string($scope) && ctype_digit($scope)) {
return (int) $scope;
}
throw UnresolvableScope::cannotNormalize($scope);
}
public function exists(int $scope): bool
{
// Must bypass your own tenant global scopes: this runs on queues and in console
return Tenant::query()->withoutGlobalScopes()->whereKey($scope)->exists();
}
}
// app/Providers/AppServiceProvider.php
use App\Search\TenantScope;
use Core45\ScoutPostgres\Contracts\ScopeRepository;
use Core45\ScoutPostgres\Contracts\ScopeResolver;
public function register(): void
{
$this->app->singleton(ScopeResolver::class, TenantScope::class);
$this->app->singleton(ScopeRepository::class, TenantScope::class);
}
Note that this normalize() validates rather than casts: ->options(['scope' => ...]) passes every non-integer value to it, and casting '1-not-authorized' with (int) would yield tenant 1. Scope keys are always integers. The rules the engine enforces:
- A search with no explicit scope uses
ScopeResolver::current(). If no tenant can be resolved, it throws UnresolvableScope; it never searches every tenant and never returns an empty result to hide the problem.
- Your source models must have the tenant column on their own table, and it must be loaded: a model loaded with a partial
select() that omits it throws. A model whose tenant value is genuinely empty is skipped.
- Source keys must be unique across tenants. The unique index is
(searchable_type, searchable_id, locale) and deliberately excludes the tenant.
- When
ScopeRepository::exists() reports a tenant gone, reconciling purges its documents, whatever your on_delete setting.
Search results are loaded from your own tables, which often sit behind your own tenant global scopes. If those scopes throw when no tenant is bound, for example on a queue, list their names so the package removes them when loading results, when the sync job reloads a model and when looking for orphans; it still applies its own tenant predicate to the source table. scout-postgres:reindex loads models without removing any scope, so those scopes must not throw there:
// config/scout-postgres.php
'hydration' => [
'strip_global_scopes' => ['tenant'], // the names of YOUR global scopes
],
Reads across all tenants are allowed, but must be asked for by name with CrossScope::platformWide() and a reason:
use Core45\ScoutPostgres\Scope\CrossScope;
use Core45\ScoutPostgres\Search\SearchIndexStatistics;
$stats = app(SearchIndexStatistics::class);
$across = CrossScope::platformWide('admin dashboard corpus size');
$stats->total($across);
$stats->countsByLocale($across);
$stats->withEmbedding($across);
$stats->countsByType($across, [SearchableType::Product, SearchableType::Post]);
$stats->countForScopeAndType($tenant->id, SearchableType::Product);
Index maintenance
use Core45\ScoutPostgres\Search\SearchIndexer;
use Core45\ScoutPostgres\Search\SearchReconciliation;
app(SearchReconciliation::class)->orphanCounts($scope, [SearchableType::Product]);
app(SearchReconciliation::class)->pruneOrphans($scope, [SearchableType::Product]);
// Empty one tenant's corpus entirely (multi-tenant only)
app(SearchIndexer::class)->purgeScope($tenant->id);
Orphans are documents whose source row no longer exists; scout-postgres:reindex --prune removes them for you.
Testing
tsvector, pg_trgm and pgvector have no SQLite equivalent, so tests that exercise search need real PostgreSQL with the three extensions; the pgvector/pgvector:pg17 Docker image has them. On SQLite the migrations do nothing and searches return empty results, which keeps the rest of your suite running but proves nothing about search. To exercise the semantic branch in tests, bind a deterministic EmbeddingProvider of your own. The package's own suite runs like this:
docker run --rm -d -p 5432:5432 \
-e POSTGRES_DB=testing -e POSTGRES_USER=postgres -e POSTGRES_PASSWORD=postgres \
pgvector/pgvector:pg17
vendor/bin/pest --testsuite=Unit,Feature
vendor/bin/pest --testsuite=SingleTenant
Two runs, not one: RefreshDatabase migrates once per process, and the single-tenant suite needs its own table built with scope.mode => 'none'.
- Full-text, trigram and
filters lookups are served by GIN indexes. Range filters are not index-served.
- The semantic branch is an exact cosine-distance scan, by design, so its cost grows with the number of embedded rows in the tenant and type you search.
- Each branch fetches four times the requested limit before fusion.
- Query embeddings are cached, and provider failures are cached briefly, so an outage costs one attempt per interval rather than one per search.
- Bodies are truncated to 100,000 characters by default, because
to_tsvector fails above 1 MB of input and silently drops word positions past 16,383, which would rank long documents wrongly.
- The trigram threshold uses
word_similarity, which suits short queries against multi-word titles far better than similarity.
Troubleshooting
If search returns nothing, check in this order:
- Is the connection PostgreSQL? Off PostgreSQL the engine returns empty results and indexes nothing.
- Are
vector, pg_trgm and unaccent installed?
- Is the model's
DocumentType registered in types?
- Did
toSearchDocuments() return documents rather than [], and is a queue worker running the sync job?
- Is the locale right? Non-translatable types are stored under
'*'.
- For semantic results: is a real
EmbeddingProvider bound, and has the backfill run since the text last changed?
Other common mistakes:
UnresolvableScope on every search: multi-tenant mode with no ScopeResolver bound, or no tenant in the current context. Pass options(['scope' => $id]) or bind one.
- A
where() that matches nothing: the key is not in the document's filters.
- Full-text matches disappeared after a configuration change:
text_search changed without a reindex.
- Semantic results vanished after a model change: the fingerprint changed and the backfill has not caught up.
- Models with UUID or ULID keys: not supported.
- Wrong
SEARCH_EMBEDDING_DIMENSIONS: the column type is fixed when you migrate; set it first.
Upgrading
Version 1.1.0 fixed nine defects found in an independent review of 1.0.0, including one that could cross tenants: a malformed scope string such as '1-not-authorized' was cast to tenant 1. Anyone running 1.0.0 in multi-tenant mode should upgrade. Since 1.1.0, string scopes go through ScopeResolver::normalize(), --scope accepts only integer keys, a model without its tenant column loaded throws instead of being skipped, and documents are purged when their tenant no longer exists. Version 1.1.1 changed no code: it moved the bundled Laravel Boost skill to resources/boost/skills/scout-postgres-development/, where php artisan boost:install can find it.
Three changes need more than composer update: changing text_search needs a full reindex; changing the embedding model needs a new fingerprint and a backfill; and changing vector.dimensions after rows exist is not a Schema::table() change. The package documents no procedure for this, so treat a width change as a schema change you plan yourself, followed by a full backfill.
Licence
MIT.
Source, issues and contributions
The code, the tests, the architecture decision record and the issue tracker are in the GitHub repository. Bug reports and pull requests are welcome there. We also build custom web applications on Laravel for clients. If your team wants search built into its application, get in touch.