Search
- Introduction
- Configuration
- Making models searchable
- Searching
- Semantic search
- Keeping the index in sync
- Custom engines
- Testing
Introduction
The search package can add full-text and semantic search to your models. For example, a blog might let readers search posts by title and body while showing only published entries. You tag the fields a search should read on your model, and search.Query returns the matching models, ready to filter, order, and paginate like any model query:
// models/post.go
package models
import "time"
type Post struct {
ID int64 `json:"id"`
UserID int64 `json:"user_id" search:"filterable"`
Title string `json:"title" search:"text,weight=3"`
Body string `json:"body" search:"fulltext"`
Published bool `json:"published" search:"filterable"`
CreatedAt time.Time `json:"created_at" search:"filterable,sortable"`
UpdatedAt time.Time `json:"updated_at"`
}A handler then passes the reader's search terms to search.Query to retrieve the matching posts:
posts, err := search.Query[models.Post](terms).
WhereEq("published", true).
Limit(15).
Get(r)By default, Laravel uses the database engine, which runs each search directly against the model's table using like conditions and your database's full-text indexes on PostgreSQL, MySQL, and MariaDB. Because it requires no extra service and no separate copy of your data, it's a great place to get started.
When your application outgrows database search, such as when readers expect typo tolerance or a table holds millions of rows, you may switch to Meilisearch, Typesense, or Turbopuffer by changing your environment variables. These services keep a dedicated index of your searchable rows, and Laravel keeps that index in sync when your models change. Your model definitions and search queries stay the same across engines.
Configuration
List a zero value of each searchable model in Searchable inside bootstrap/app.go:
// bootstrap/app.go
Searchable: []any{models.Post{}},Laravel validates each listed model's search tags when the application starts and returns an error if a model has no search tags or uses an unknown tag.
Laravel reads your search settings from environment variables. The defaults work for most applications:
| Variable | Default | What it does |
|---|---|---|
SEARCH_ENGINE | database | Selects the search engine: database, meilisearch, typesense, turbopuffer, or discard. |
SEARCH_QUEUE | false | Runs index syncs from a queued job instead of during the request. |
SEARCH_PREFIX | No prefix | Prepends text, such as staging_, to every index name and sync lock key so applications that share a search service or cache don't collide. |
Search engines
The database engine searches PostgreSQL, MySQL, MariaDB, and SQLite directly and needs no extra environment variables. When you want to disable indexing and searching, such as on a staging server that shares production's database, set SEARCH_ENGINE=discard. The discard engine stores nothing, finds nothing, and embeds nothing, so it never calls your embedder.
To use a dedicated search service, set SEARCH_ENGINE along with that service's credentials in your .env file.
Meilisearch
Meilisearch is an open-source search engine that you may self-host or run on Meilisearch Cloud. Set SEARCH_ENGINE, your server URL, and your master or API key:
SEARCH_ENGINE=meilisearch
MEILISEARCH_HOST=http://127.0.0.1:7700
MEILISEARCH_KEY=masterKeyMEILISEARCH_HOST defaults to http://localhost:7700. You may leave MEILISEARCH_KEY unset for a local server started without a master key.
Typesense
Typesense is an open-source search engine that you may self-host or run on Typesense Cloud. Set SEARCH_ENGINE along with your server's host, port, protocol, and API key:
SEARCH_ENGINE=typesense
TYPESENSE_HOST=127.0.0.1
TYPESENSE_PORT=8108
TYPESENSE_PROTOCOL=http
TYPESENSE_API_KEY=xyzTYPESENSE_HOST defaults to localhost, TYPESENSE_PORT defaults to 8108, and TYPESENSE_PROTOCOL defaults to http.
Turbopuffer
Turbopuffer is a hosted search engine built on object storage. Set SEARCH_ENGINE, your API key, and your region if it differs from the default gcp-us-central1:
SEARCH_ENGINE=turbopuffer
TURBOPUFFER_API_KEY=tpuf_your_key
TURBOPUFFER_REGION=gcp-us-central1Creating indexes
Dedicated search engines track index settings derived from your search tags, such as which fields are searchable, filterable, and sortable. Run search:index to create missing indexes and push those settings:
laravel search:indexWhether you need to run search:index up front depends on the engine:
- Meilisearch requires
search:indexbefore filtering, sorting, or using embedders, because Meilisearch rejects filters and sorts until those settings are pushed. Laravel waits for the settings update to finish so searches immediately after a deploy use them. - Typesense creates a missing collection automatically on the first write, so you only need
search:indexwhen adding new tagged fields to an existing collection. - Turbopuffer creates the namespace and applies your schema automatically on every write, so you can start writing documents immediately without running
search:indexfirst (running it pushes schema changes ahead of the next write). databaseanddiscardkeep no separate indexes, sosearch:indexandsearch:delete-indexreport that there is nothing to do.
Neither Typesense nor Turbopuffer can change the type of an existing field, so after changing a tagged field's Go type, run search:delete-index, search:index, and search:import to rebuild the index. Running search:index again is safe when nothing changed, so you may still include it in your deploy script before search:import.
To create or update indexes for specific models, pass their names:
laravel search:index PostSearching an index that doesn't exist yet returns empty results rather than failing, so pages keep working before your first import. If searches on a new server find nothing at all, check that SEARCH_PREFIX matches the prefix used when creating the indexes.
To delete an index along with all of its documents and settings, such as after renaming an index with SearchIndex, run search:delete-index with the model's name or the index's name. SEARCH_PREFIX is added automatically unless the name already starts with it:
laravel search:delete-index Post
laravel search:delete-index old_postsWhen the index doesn't exist, the command says there's nothing to delete and still succeeds, so deploy scripts that clean up old indexes can run safely more than once.
Making models searchable
To make a model searchable, add search struct tags to the fields that searches read and list a zero value of the model in Searchable in bootstrap/app.go:
// models/post.go
package models
type Post struct {
ID int64 `json:"id"`
Title string `json:"title" search:"text"`
Published bool `json:"published" search:"filterable"`
}Search tags
A search reads only the fields you tag, so untagged columns such as stripe_customer_id stay out of your index. Tagging a field text marks it as searchable text. To rank matches in one text field higher than another (on engines that support field weights), add weight=N:
// models/post.go
package models
type Post struct {
ID int64 `json:"id"`
Title string `json:"title" search:"text,weight=3"`
Body string `json:"body" search:"text"`
}Filtering and ordering also require tags, because a search can only filter or sort on fields that the index tracks. Tag a field filterable to make it filterable in search queries, and sortable to make it sortable. Combine tags with commas, such as search:"filterable,sortable" or search:"text,filterable".
Each search tag controls how the index treats that field:
| Tag | Purpose |
|---|---|
text | Marks the field as searchable text. |
weight=N | Ranks matches in this text field higher than lighter fields on engines that support weights. |
filterable | Makes the field available for search filters. |
sortable | Makes the field available for sorting search results. |
Text tags apply to string fields, and every searchable model needs at least one. filterable and sortable apply to strings, numbers, booleans, time.Time fields, and types that marshal to text such as uuid.UUID. The model's primary key is always indexed and can be filtered or sorted without a tag. Primary keys can't be tagged for text search; if a query might be an ID, look the row up by primary key in your handler instead.
Engine-specific behavior
While your model definitions and search queries stay the same across engines, each engine has its own strengths and nuances when matching text, indexing fields, and sorting results. Keep the following details in mind when choosing or switching engines.
Database
On the database engine, text runs a case-insensitive substring like match (%terms%) and weight=N is ignored. For better performance or stricter matching on database queries, you may use two additional text tags:
prefixruns a prefixlikematch (terms%) that can use a standard index, which fits fields such as email addresses or slugs.fulltextruns a word-based full-text search ranked by relevance, which fits long text such as bios or article bodies.
// models/user.go
package models
type User struct {
ID int64 `json:"id"`
Name string `json:"name" search:"text"`
Email string `json:"email" search:"prefix"`
Bio string `json:"bio" search:"fulltext"`
}Dedicated engines treat prefix and fulltext the same as text, because they already handle tokenization, prefix matching, and full-text indexing automatically.
A fulltext field requires a full-text index on PostgreSQL, MySQL, and MariaDB. Create it in a migration with table.FullText:
table.Text("body")
table.FullText("body")Meilisearch and Typesense
Meilisearch and Typesense match whole words and word prefixes with typo tolerance rather than arbitrary substrings, so onara won't match "Editorial Carbonara", while otw matches "Taylor Otwell".
On Typesense, primary keys are stored as text, so searches can't sort by the primary key or filter it with WhereLt, WhereLe, WhereGt, or WhereGe (only WhereEq, WhereNe, WhereIn, and WhereNotIn).
Turbopuffer
Turbopuffer matches whole words and treats the last word of the search terms as a prefix. Turbopuffer does not support sorting queries that have search terms, so OrderBy, Latest, and Oldest return an error there unless the search terms are blank.
Naming the index
By default, each searchable model's index is named after its table, with SEARCH_PREFIX in front. On the database engine, the index is the table itself. If you'd like a different index name, such as when two models share one table, define a SearchIndex method on the model:
func (Post) SearchIndex() string {
return "articles"
}Choosing which rows are searchable
By default, every row in the model's table is searchable. When only some rows should appear in search results, such as published posts and never drafts, define a SearchIndexed method on the model. It receives the model's query and narrows it. Every search, sync, and import starts from the query it returns, so drafts never appear even without WhereEq("published", true):
func (Post) SearchIndexed(q *model.Builder[Post]) *model.Builder[Post] {
return q.WhereEq("published", true)
}Because SearchIndexed uses an ordinary model query, it supports any condition as well as eager loading with With.
Searching
Call search.Query with the model type and the terms to look for, then run it with a terminal method such as Get, First, Keys, Paginate, or SimplePaginate. By default, results are ranked by relevance. For example, this handler reads the q query parameter using r.Query and returns the matching posts as JSON:
// handlers/posts/index.go
package posts
import (
"go.laravel.com/search"
"go.laravel.com/web"
"app/models"
)
type PostSearch struct {
Q string `json:"q"`
}
func Index(r *web.Request) *web.Response {
params, err := r.Query[PostSearch]()
if err != nil {
return web.Fail(err)
}
posts, err := search.Query[models.Post](params.Q).Get(r)
if err != nil {
return web.Fail(err)
}
return web.JSON(posts)
}Besides Get, you may fetch only the best match, cap the number of results, or retrieve only the matching primary keys without loading the models:
post, err := search.Query[models.Post]("carbonara").First(r)
posts, err := search.Query[models.Post]("carbonara").Limit(5).Get(r)
ids, err := search.Query[models.Post]("carbonara").Keys(r)First returns a *db.NotFoundError (which responds with a 404) when nothing matches. To paginate results, call Paginate or SimplePaginate, as covered in Pagination.
Filtering and ordering
A search accepts the same filter conditions as a model query. Use WhereEq, WhereNe, WhereLt, WhereLe, WhereGt, and WhereGe to compare a column with a value, and WhereIn or WhereNotIn to compare against a slice of values:
posts, err := search.Query[models.Post](terms).
WhereEq("published", true).
WhereNe("user_id", user.ID).
WhereGe("created_at", time.Now().AddDate(0, 0, -30)).
Limit(20).
Get(r)By default, results are ranked by relevance. If your search page lets users override relevance ranking (for example, sorting matching posts newest first or sorting products by price), call OrderBy, OrderByDesc, Latest, or Oldest:
posts, err := search.Query[models.Post](terms).
WhereEq("published", true).
Latest("created_at").
Get(r)Foreign keys are among the most common filters, such as scoping documents to the current team in a multi-tenant application. Tag the foreign key search:"filterable" and filter by it on every search:
type Document struct {
ID int64 `json:"id"`
TeamID int64 `json:"team_id" search:"filterable"`
Title string `json:"title" search:"text"`
}
documents, err := search.Query[models.Document](terms).
WhereEq("team_id", team.ID).
Paginate(r, r.Page(15))Some filters apply only when the reader asks for them, such as a category picked from a menu beside the search box. Pass the condition and a function that adds the filter to When, which calls the function only when the condition is true, so the search keeps one chain instead of reassigning a variable:
type PostSearch struct {
Q string `json:"q"`
Category string `json:"category"`
}
params, err := r.Query[PostSearch]()
if err != nil {
return web.Fail(err)
}
posts, err := search.Query[models.Post](params.Q).
WhereEq("published", true).
When(params.Category != "", func(
q *search.Builder[models.Post],
) *search.Builder[models.Post] {
return q.WhereEq("category", params.Category)
}).
Paginate(r, r.Page(15))Pass each filter a value of the field's type, such as an integer for team_id, a bool for published, or a time.Time for created_at. Laravel sends the value to the engine as you pass it, converting a time.Time to the Unix seconds the index holds, so parse a date or a number read from the query string before you filter by it.
Each Where method adds a condition that every match must pass. To match any of several values of one field, such as posts in either of two categories, use WhereIn:
posts, err := search.Query[models.Post](terms).
WhereEq("published", true).
WhereIn("category", []string{"go", "rust"}).
Get(r)A search may filter only by the primary key or fields tagged filterable, and sort only by the primary key or fields tagged sortable.
Loading relationships
Because a search returns ordinary models, you may eager-load their relationships with With, as you would on a model query:
posts, err := search.Query[models.Post](terms).
With("user").
Paginate(r, r.Page(15))To eager-load a relationship on every search of the model, call With inside SearchIndexed.
Pagination
To paginate search results, call Paginate or SimplePaginate. Both return the same *pagination.Paginator and *pagination.SimplePaginator types described in the pagination guide. Their page links keep the request's entire query string, so page 2 of /posts?q=carbonara&sort=new links to /posts?q=carbonara&sort=new&page=2:
posts, err := search.Query[models.Post](terms).
WhereEq("published", true).
Paginate(r, r.Page(15))Paginate counts every matching row so it can display the total number of pages. If you only need previous and next links, call SimplePaginate to skip the count.
Engine options
Each search service offers features that Laravel doesn't wrap, such as Meilisearch's facets for counting matches per field value. Pass the service's own parameters with Options, which merges them into the outgoing request, and call Raw when you need the service's full JSON response as a map[string]any. The database engine sends no request, so a search with Options or Raw returns an error there. In this example, a handler counts matching posts by author:
results, err := search.Query[models.Post](terms).
Options(map[string]any{"facets": []string{"user_id"}}).
Raw(r)
if err != nil {
return web.Fail(err)
}
return web.JSON(results["facetDistribution"])Any option with the same name as a parameter Laravel sends replaces Laravel's value. For example, passing Meilisearch's filter or Typesense's filter_by replaces Laravel's generated filters, and passing a paging option such as per_page overrides Limit and Paginate.
Passing a native filter option is also how you express OR conditions across different fields. Because it replaces every filter Laravel builds (including tenant filters such as team_id), include all required conditions in the expression. For example, on Meilisearch, with team_id, shared, and owner_id tagged filterable:
filter := fmt.Sprintf(
"team_id = %d AND (shared = true OR owner_id = %d)",
team.ID,
user.ID,
)
documents, err := search.Query[models.Document](terms).
Options(map[string]any{"filter": filter}).
Get(r)Semantic search
A text search finds posts that contain the reader's words, but readers often describe what they want in different words. Someone typing "pasta recipes" wants your post titled "How I make carbonara" even though it never uses the word "pasta".
Semantic search matches posts by meaning. An embedding model converts each post's text into an embedding, a list of numbers that places texts with similar meanings close together, and each search compares the reader's terms against the stored embeddings.
Embedding your models
To make a model searchable by meaning, define SearchEmbeddingDimensions on it, returning the number of dimensions your embedding model produces, such as 1,536 for OpenAI's text-embedding-3-small:
// models/post.go
func (Post) SearchEmbeddingDimensions() int {
return 1536
}How Laravel stores those vectors depends on your search engine:
- Meilisearch, Typesense, and Turbopuffer store each model's embedding directly in the search index alongside its other fields, so your database table needs no
embeddingcolumn. After addingSearchEmbeddingDimensions, runsearch:index(on Meilisearch and Typesense) so the index includes the vector field, then runsearch:importto embed existing rows. databasestores each model's embedding in a vector column namedembeddingon the model's table (supported on PostgreSQL with pgvector and MariaDB 11.7+).
Storing embeddings in your database
If you're using the database engine, add a nullable embedding vector column with the same number of dimensions in a migration. Your model struct doesn't need a field for it. On PostgreSQL, call schema.EnsureVectorExtension first to install pgvector if needed:
// database/migrations/2026_11_21_090000_add_embedding_to_posts_table.go
func addEmbeddingToPostsTable(ctx context.Context) error {
if err := schema.EnsureVectorExtension(ctx); err != nil {
return err
}
return schema.Alter(ctx, "posts", func(table *schema.Blueprint) {
table.Vector("embedding", 1536).Nullable()
})
}On PostgreSQL, you may chain .Index() (or call table.VectorIndex("embedding")) to add an HNSW vector index for faster semantic searches on large tables. To learn more, check out the schema builder guide's section on vector columns:
table.Vector("embedding", 1536).Nullable().Index()Registering an embedder
Laravel doesn't call an embedding provider itself, so implement search.Embedder (returning one db.Vector per input text in the same order) and register it as SearchEmbedder in bootstrap/app.go:
// services/embedder.go
package services
import (
"context"
"go.laravel.com/db"
)
type Embedder struct{}
func (Embedder) Embed(ctx context.Context, texts []string) ([]db.Vector, error) {
// Generate embeddings with OpenAI or another provider...
return nil, nil
}// bootstrap/app.go
return laravel.Options{
SearchEmbedder: services.Embedder{},
// ...
}Once registered, Laravel embeds a model whenever it syncs (up to 100 rows per call). On the database engine, Laravel still embeds models after model.Create and after updates to tagged fields, saving the vector to the embedding column without triggering another sync. To embed rows that already exist, run search:import.
Customizing the embedded text
By default, Laravel embeds all non-empty text fields tagged text, prefix, or fulltext, joined with blank lines. Untagged columns are never embedded or sent to the index.
To customize the text that gets embedded (for example, embedding only the title when bodies exceed your model's token limit), define SearchEmbeddingInput. Because Laravel can't tell which fields SearchEmbeddingInput reads, defining it syncs on every update unless you also define SearchNeedsReindex:
func (p Post) SearchEmbeddingInput() string {
return p.Title
}When the text to embed is blank, Laravel skips calling your embedder and clears the model's stored embedding.
Searching by meaning
Call Semantic to rank posts by how close their stored embedding is to the embedding of the reader's terms, most similar first. Laravel embeds the terms when the search runs and doesn't match the post's text directly, so "pasta recipes" finds the carbonara post:
posts, err := search.Query[models.Post]("pasta recipes").
Semantic().
Limit(10).
Get(r)Closeness is measured by cosine similarity, where 1 represents identical meaning and values fall toward 0 for unrelated text. On the database engine, a semantic search keeps posts whose similarity is at least 0.4 by default. Meilisearch, Typesense, and Turbopuffer rank every post by similarity, without a cutoff of their own. Pass MinSimilarity to set the cutoff yourself. Turbopuffer has no similarity cutoff, so MinSimilarity returns an error there:
posts, err := search.Query[models.Post](q).
Semantic().
MinSimilarity(0.5).
Paginate(r, r.Page(15))On Meilisearch, MinSimilarity is a threshold on Meilisearch's ranking score rather than on cosine similarity, and a post with an unrelated meaning scores about 0.5 there.
Because each embedding model distributes cosine similarity scores differently, you may need to tune MinSimilarity against your own data by testing a few sample queries and raising the threshold where irrelevant results begin.
Filters, With, Limit, and all terminal methods work as they do in a text search. Because similarity determines the order, calling OrderBy, OrderByDesc, Latest, or Oldest on a semantic search returns an error naming the conflict. A semantic or hybrid search with empty terms also returns an error, so fall back to text search when the search box is empty.
Hybrid search
A semantic search can miss a post that contains an exact keyword or product code, while a text search misses posts that express the same idea in different words. Calling Hybrid combines both, merging the text ranking and the semantic ranking so posts that score well in both appear first:
posts, err := search.Query[models.Post](q).
Hybrid().
Paginate(r, r.Page(15))Text and semantic rankings carry equal weight by default (1 and 1). To emphasize one over the other, call Weights with the text weight followed by the semantic weight. The numbers are relative: passing 1 and 2 gives semantic meaning twice as much influence as text matching, which works well in a help center where readers rarely guess your exact terminology:
posts, err := search.Query[models.Post](q).
Hybrid().
Weights(1, 2).
Paginate(r, r.Page(15))MinSimilarity sets the minimum similarity for the semantic half of a hybrid search, so a post that matches neither the reader's words nor their meaning never appears.
Each engine merges the two rankings its own way, so the same search may order posts differently on each.
Letting the engine embed
If you prefer not to call an embedding provider from your application, Meilisearch, Typesense, and Turbopuffer can generate embeddings for your documents and search terms themselves. Your model only needs its standard search tags, with no SearchEmbeddingDimensions method and no SearchEmbedder registered:
// models/post.go
package models
type Post struct {
ID int64 `json:"id"`
Title string `json:"title" search:"text,weight=3"`
Body string `json:"body" search:"text"`
}Once you configure the embedding environment variable for your chosen engine using one of the examples below, Semantic() and Hybrid() will work automatically.
Typesense
Set TYPESENSE_EMBEDDING_MODEL to a model Typesense supports, such as its built-in ts/all-MiniLM-L12-v2, then run laravel search:index. The command adds an embedding field that Typesense computes from your model's text fields:
TYPESENSE_EMBEDDING_MODEL=ts/all-MiniLM-L12-v2Turbopuffer
Set TURBOPUFFER_EMBEDDING_MODEL to one of Turbopuffer's embedding models available in your region. Laravel writes each post's text fields, joined with blank lines, to an embedding_input attribute that Turbopuffer embeds:
TURBOPUFFER_EMBEDDING_MODEL=openai/text-embedding-3-smallBecause Turbopuffer bills per embedded token, run laravel search:import once to embed existing rows rather than on every deploy. If the namespace already holds documents from before you set TURBOPUFFER_EMBEDDING_MODEL, rebuild the namespace with search:delete-index, search:index, and search:import.
Meilisearch
Set MEILISEARCH_EMBEDDING_SOURCE to huggingFace for a Hugging Face model that Meilisearch runs itself, or to openAi, and name the model in MEILISEARCH_EMBEDDING_MODEL. An OpenAI model also requires MEILISEARCH_EMBEDDING_API_KEY:
MEILISEARCH_EMBEDDING_SOURCE=huggingFace
MEILISEARCH_EMBEDDING_MODEL=BAAI/bge-small-en-v1.5MEILISEARCH_EMBEDDING_SOURCE=openAi
MEILISEARCH_EMBEDDING_MODEL=text-embedding-3-small
MEILISEARCH_EMBEDDING_API_KEY=sk-your-keyBecause Meilisearch stores embedder configuration in each index's settings, run laravel search:index (even on a new application with no data yet) to register the embedder on your searchable indexes. Meilisearch embeds the first 400 bytes of each model's tagged text fields, joined with blank lines.
If you later change the source, model, or tagged text fields (or unset MEILISEARCH_EMBEDDING_SOURCE), run laravel search:index again to update or remove the embedder.
If you'd rather configure an embedder yourself (such as one with a custom documentTemplate, as Meilisearch's AI-powered search guide describes), set MEILISEARCH_EMBEDDER to its name instead, and search:index leaves its settings untouched:
MEILISEARCH_EMBEDDER=postsKeeping the index in sync
Whenever your application calls model.Create, model.Update, model.Save, or model.Delete on a searchable model, Laravel syncs the row after the write's database transaction commits. If a transaction rolls back, nothing syncs.
Typesense and Turbopuffer reflect a synced write as soon as it returns. Meilisearch applies writes asynchronously in the background, so a new or updated post may take a moment to appear in search results after model.Create or model.Update returns.
Each sync re-reads the row through SearchIndexed. If SearchIndexed still returns the row, Laravel sends its tagged fields to the index. If it doesn't, such as when a post is unpublished or deleted, Laravel removes the row from the index.
A model with only search tags syncs on an update only when a tagged field changed, so calling model.Increment(r, &post, "views", 1) on every page view skips syncing. A model that defines SearchIndexed or SearchEmbeddingInput syncs on every update, because an update to any column could change whether the row belongs in the index or what it contains. To name the columns that trigger a sync instead, define SearchNeedsReindex:
func (Post) SearchNeedsReindex(e model.Updated[Post]) bool {
for _, column := range []string{"title", "body", "published"} {
if _, ok := e.Changed(column); ok {
return true
}
}
return false
}If the search engine fails during a sync, such as when the search service is unreachable, the database write still succeeds because the row is already saved and retrying the request could save it twice. model.Create and the other model writes return nil, inside or outside db.Transaction, and Laravel reports the sync error to your application's error reporter. For automatic retries during brief outages, enable queued syncs. Once the service recovers, call search.Sync or run search:import to send missed rows. Because you call search.Sync directly, it returns sync errors to the caller.
The database engine queries your tables directly and has no separate index to sync, except for the embeddings of a model that defines SearchEmbeddingDimensions.
Queueing syncs
By default, Laravel syncs the index during the request that writes the model. In production, set SEARCH_QUEUE=true so syncs run on your queue and a slow search service never delays web requests:
SEARCH_QUEUE=trueA queued sync carries the model's key and re-reads the row when a worker runs it, so the index receives the latest saved version. When an editor autosaves a post several times in a few seconds, Laravel debounces single-row syncs for 5 seconds (up to 1 minute maximum) before running. If the search service is temporarily unavailable, queued syncs retry up to 10 times with a 1, 5, and 30 second backoff before moving to the failed jobs table with an error naming the model and keys (such as search: syncing models.Post 42: ...).
Each single-row sync also acquires a lock on that row in your default cache store so an older, slower sync can't overwrite a newer one. If a queued sync finds the row locked, it releases back onto the queue and tries again a second later, which counts as one of its 10 tries. Because both debouncing and row locks live in your cache, use a shared cache store such as database or redis in production.
To adjust the debounce windows, set cfg.Search.DebounceFor and cfg.Search.MaxWait in a Configure callback on laravel.Options in bootstrap/app.go:
// bootstrap/app.go
return laravel.Options{
Configure: func(cfg *config.Config, env *config.Env) {
cfg.Search.DebounceFor = 10 * time.Second
cfg.Search.MaxWait = 2 * time.Minute
},
// ...
}Writes that skip model events
Bulk query operations such as db.Table("posts").Update or Insert don't dispatch model events, so Laravel doesn't sync them automatically. After running a bulk write, pass a model, a slice of models, or a model query to search.Sync:
_, err := db.Table("posts").
WhereEq("user_id", user.ID).
Update(r, db.Values{"published": false})
if err != nil {
return web.Fail(err)
}
err = search.Sync(r, model.Query[models.Post]().WhereEq("user_id", user.ID))search.Sync extracts the primary keys from the model, slice, or query you pass, re-queries the database through SearchIndexed in chunks of 500, upserts the rows that still match, and removes any keys that no longer exist or no longer match SearchIndexed. When SEARCH_QUEUE=true, it dispatches one queued job per 500 rows without debouncing.
A query finds only rows that still exist, so after a bulk delete, a query passed to search.Sync can't find the deleted posts to remove them. Read their keys before deleting them, then pass search.Sync posts that hold only those keys. Each sync reads its rows again when it runs, and removes the keys whose rows are gone:
posts := model.Query[models.Post]().WhereEq("user_id", user.ID)
ids, err := posts.Pluck[int64](r, "id")
if err != nil {
return web.Fail(err)
}
if _, err := posts.Delete(r); err != nil {
return web.Fail(err)
}
deleted := make([]models.Post, len(ids))
for i, id := range ids {
deleted[i] = models.Post{ID: id}
}
err = search.Sync(r, deleted)Pausing syncing
When you need to write many rows without syncing each one individually, such as inside a seeder that imports the whole table afterward, pass a context wrapped with search.Muted:
muted := search.Muted(ctx)
for _, post := range posts {
if err := model.Create(muted, &post); err != nil {
return err
}
}Because search.Muted returns a derived context without modifying ctx, any later writes using ctx continue to sync normally. Other model event listeners continue to receive the writes' events, and calling search.Sync explicitly still syncs a muted context's rows. To skip every event listener including syncing, use event.Muted.
Importing and flushing
When you make an existing model searchable or change its tags, run search:import with the model's name (such as Post or models.Post) to upsert every row returned by SearchIndexed in chunks of 500, updating existing documents in place. When SEARCH_QUEUE=true, Laravel queues one job per 500 rows instead. Pass --fresh to clear the index first (for example, to remove stale documents that no longer match SearchIndexed):
laravel search:import Post
laravel search:import Post --freshTo remove every document from a model's index without re-importing, run search:flush:
laravel search:flush PostFor a model that defines SearchEmbeddingDimensions, search:import also regenerates embeddings for every row (including on the database engine, where it populates the embedding column). Run it after switching embedding models or changing the text a model embeds. Because Laravel calls your embedding provider in batches of 100 rows, importing a large table may take a while.
Custom engines
If you want to use a search service that Laravel doesn't ship with, such as Algolia, implement search.Engine. An engine stores documents and answers searches with matching keys. Laravel converts each query into a search.Request, validates filters and sorts against your tags, and loads the models for the keys the engine returns, so an engine never sees a model or a database query:
type Engine interface {
Upsert(
ctx context.Context,
index *search.Index,
documents []search.Document,
) error
Delete(ctx context.Context, index *search.Index, keys []any) error
Search(
ctx context.Context,
index *search.Index,
request search.Request,
) (search.Hits, error)
Flush(ctx context.Context, index *search.Index) error
SyncIndex(ctx context.Context, index *search.Index) error
DeleteIndex(ctx context.Context, name string) (bool, error)
}The search.Index describes the model's tagged fields so your engine can derive its settings from them. SyncIndex creates the index when it's missing and sends those settings, and search:index calls it for each searchable model. Register your engine by name in the Register option of bootstrap/app.go, then select it with SEARCH_ENGINE=algolia:
// bootstrap/app.go
return laravel.Options{
// ...
Register: func(app *laravel.Registrar) error {
app.SearchEngine("algolia", algolia.New())
return nil
},
}A package registers a search engine the same way inside its Register method with app.SearchEngine. An engine registered in bootstrap/app.go overrides a package's engine of the same name.
Testing
We recommend running your tests on the database engine. It searches your test database, so a test can create posts and search for them without a search service. New applications set SEARCH_ENGINE to database in tests/tests.go:
// tests/tests.go
laraveltest.Env(map[string]string{
// ...
"SEARCH_ENGINE": "database",
// ...
}),In this example, a test creates two posts and searches for the published one:
// tests/feature/search_test.go
package feature_test
import (
"testing"
"go.laravel.com/search"
"app/database/factories"
"app/models"
"app/tests"
)
func TestSearchesFindOnlyPublishedPosts(t *testing.T) {
client := tests.New(t)
client.Create(factories.Post, func(p *models.Post) {
p.Title, p.Published = "Carbonara at home", true
})
client.Create(factories.Post, func(p *models.Post) {
p.Title, p.Published = "Draft about carbonara", false
})
posts, err := search.Query[models.Post]("carbonara").
WhereEq("published", true).
Get(client.Context())
if err != nil || len(posts) != 1 || posts[0].Title != "Carbonara at home" {
t.Errorf("found %v, %v, want only the published post", posts, err)
}
}If most of your tests don't care about search, you may set SEARCH_ENGINE to discard in tests/tests.go instead. The discard engine keeps nothing and finds nothing, and Laravel embeds nothing on it, so creating a model that defines SearchEmbeddingDimensions doesn't call your embedder. A test that searches then sets the database engine again with laraveltest.Env(map[string]string{"SEARCH_ENGINE": "database"}).
Testing against a dedicated engine
Engine-specific behavior, such as Typesense's typo tolerance, only shows up against the real service (see engine-specific behavior). Keep those tests in a file with a build tag such as integration, override SEARCH_ENGINE with laraveltest.Env, and set a dedicated SEARCH_PREFIX (such as test_blog_) so flushing or deleting the test index never touches your development indexes:
//go:build integration
// tests/feature/search_integration_test.go
package feature_test
import (
"testing"
"go.laravel.com/laraveltest"
"go.laravel.com/search"
"app/database/factories"
"app/models"
"app/tests"
)
func TestTypesenseToleratesTypos(t *testing.T) {
client := tests.New(t, laraveltest.Env(map[string]string{
"SEARCH_ENGINE": "typesense",
"SEARCH_PREFIX": "test_blog_",
}))
client.Command("search:flush Post").AssertSuccessful()
client.Command("search:index Post").AssertSuccessful()
// Defer deletion so it runs before the test context ends...
defer client.Command("search:delete-index Post")
client.Create(factories.Post, func(p *models.Post) {
p.Title = "Carbonara at home"
})
posts, err := search.Query[models.Post]("carbonra").Get(client.Context())
if err != nil || len(posts) != 1 {
t.Errorf("found %v, %v, want the carbonara post", posts, err)
}
}Run the tests tagged integration with -tags. A plain go test ./... leaves out files with a build tag, so your everyday test runs don't need a search service:
go test -tags integration ./...A semantic search calls your SearchEmbedder to embed the reader's terms, so put semantic searches in the integration group too.
说明
On MySQL and MariaDB, a full-text search can't see rows written inside an uncommitted transaction, and refreshed tests never commit. To test fulltext search on MySQL or MariaDB, insert the rows in a seeder with laraveltest.SeedOnce, whose rows are committed.