Search
- Introduction
- Configuration
- Making models searchable
- Searching
- Semantic search
- Keeping the index in sync
- Custom engines
- Testing
Introduction
Laravel 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 mark the fields a search should read on your model, and Post::search("rust") returns the matching posts, ready to filter, order, and paginate like any model query:
1use laravel::model::model;2use laravel::search::Searchable;3use laravel::time::Timestamp;45#[model(searchable)]6pub struct Post {7 pub id: i64,8 #[search]9 pub title: String,10 #[search(full_text)]11 pub body: String,12 #[search(filterable)]13 pub published: bool,14 #[search(filterable, sortable)]15 pub created_at: Timestamp,16 pub updated_at: Timestamp,17}1819impl Searchable for Post {}1use laravel::model::model;2use laravel::search::Searchable;3use laravel::time::Timestamp;45#[model(searchable)]6pub struct Post {7 pub id: i64,8 #[search]9 pub title: String,10 #[search(full_text)]11 pub body: String,12 #[search(filterable)]13 pub published: bool,14 #[search(filterable, sortable)]15 pub created_at: Timestamp,16 pub updated_at: Timestamp,17}1819impl Searchable for Post {}
A handler then passes the reader's search terms to Post::search to retrieve the matching posts:
1let posts = Post::search(terms)2 .filter(Post::published.eq(true))3 .limit(15)4 .get()5 .await?;1let posts = Post::search(terms)2 .filter(Post::published.eq(true))3 .limit(15)4 .get()5 .await?;
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. 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
Search is an optional Cargo feature. Enable search on laravel-rust in your application's Cargo.toml:
1[dependencies]2laravel-rust = { version = "1", features = ["database-postgres", "search"] }1[dependencies]2laravel-rust = { version = "1", features = ["database-postgres", "search"] }
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 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:
1SEARCH_ENGINE=meilisearch2MEILISEARCH_HOST=http://127.0.0.1:77003MEILISEARCH_KEY=masterKey1SEARCH_ENGINE=meilisearch2MEILISEARCH_HOST=http://127.0.0.1:77003MEILISEARCH_KEY=masterKey
MEILISEARCH_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:
1SEARCH_ENGINE=typesense2TYPESENSE_HOST=localhost3TYPESENSE_PORT=81084TYPESENSE_PROTOCOL=http5TYPESENSE_API_KEY=xyz1SEARCH_ENGINE=typesense2TYPESENSE_HOST=localhost3TYPESENSE_PORT=81084TYPESENSE_PROTOCOL=http5TYPESENSE_API_KEY=xyz
TYPESENSE_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:
1SEARCH_ENGINE=turbopuffer2TURBOPUFFER_API_KEY=your-api-key3TURBOPUFFER_REGION=gcp-us-central11SEARCH_ENGINE=turbopuffer2TURBOPUFFER_API_KEY=your-api-key3TURBOPUFFER_REGION=gcp-us-central1
Creating indexes
Dedicated search engines track index settings derived from your field marks, such as which fields are searchable, filterable, and sortable. Run search:index to create missing indexes and push those settings:
1laravel search:index1laravel search:index
Whether 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 marked 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 marked field's Rust 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 a single model's index, pass its struct name or index name (with or without SEARCH_PREFIX, so with staging_, both staging_posts and posts match Post):
1laravel search:index Post1laravel search:index Post
Searching an index that doesn't exist yet returns empty results (and null for raw) 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 searchable(index = ".."), 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:
1laravel search:delete-index Post2laravel search:delete-index old_posts1laravel search:delete-index Post2laravel search:delete-index old_posts
When the index doesn't exist, the command says there's nothing to delete and still succeeds, on every engine and for any name, so a deploy script that deletes an old index may run again.
Making models searchable
To make a model searchable, add searchable to its #[model(..)] attribute, mark the fields that searches read with #[search], and implement Searchable. Every method on Searchable has a default implementation, so an empty block is enough to start:
1// src/models/post.rs2use laravel::model::model;3use laravel::search::Searchable;45#[model(searchable)]6pub struct Post {7 pub id: i64,8 #[search]9 pub title: String,10 #[search(filterable)]11 pub published: bool,12}1314impl Searchable for Post {}1// src/models/post.rs2use laravel::model::model;3use laravel::search::Searchable;45#[model(searchable)]6pub struct Post {7 pub id: i64,8 #[search]9 pub title: String,10 #[search(filterable)]11 pub published: bool,12}1314impl Searchable for Post {}
Marking fields
A search reads only the fields you mark, so unmarked columns such as stripe_customer_id stay out of your index. A bare #[search] marks a field as searchable text. To rank matches in one text field higher than another (on engines that support field weights), pass weight:
1use laravel::model::model;2use laravel::search::Searchable;34#[model(searchable)]5pub struct Post {6 pub id: i64,7 #[search(weight = 3)]8 pub title: String,9 #[search]10 pub body: String,11}1213impl Searchable for Post {}1use laravel::model::model;2use laravel::search::Searchable;34#[model(searchable)]5pub struct Post {6 pub id: i64,7 #[search(weight = 3)]8 pub title: String,9 #[search]10 pub body: String,11}1213impl Searchable for Post {}
Filtering and ordering also require marks, because a search can only filter or order on fields that the index tracks. Mark a field filterable to make it filterable in search queries, and sortable to make it sortable. A single field may carry both:
1#[search(filterable, sortable)]2pub created_at: Timestamp,1#[search(filterable, sortable)]2pub created_at: Timestamp,
A text field may also be filterable or sortable. Write text beside filterable or sortable when a field should both match search terms and allow filtering, such as a category that readers search by typing or pick from a dropdown:
1#[search(text, filterable)]2pub category: String,1#[search(text, filterable)]2pub category: String,
Each field mark controls how the index treats that field:
| Mark | Purpose |
|---|---|
#[search] or #[search(text)] |
Marks the field as searchable text. |
#[search(weight = 3)] |
Ranks matches in this text field higher than lighter fields on engines that support weights. |
#[search(filterable)] |
Makes the field available for search filters. |
#[search(sortable)] |
Makes the field available for ordering search results. |
Text marks apply to String fields, while filterable and sortable apply to any scalar column. The model's primary key is always indexed and can be filtered or ordered without a mark. Primary keys can't be marked 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, a bare #[search] runs a case-insensitive substring LIKE match (%terms%) and weight is ignored. For better performance or stricter matching on database queries, you may use two additional text marks:
#[search(prefix)]runs a prefixLIKEmatch (terms%) that can use a standard index, which fits fields such as email addresses or slugs.#[search(full_text)]runs a word-based full-text search ranked by relevance, which fits long text such as bios or article bodies.
1use laravel::model::model;2use laravel::search::Searchable;34#[model(searchable)]5pub struct User {6 pub id: i64,7 #[search]8 pub name: String,9 #[search(prefix)]10 pub email: String,11 #[search(full_text)]12 pub bio: String,13}1415impl Searchable for User {}1use laravel::model::model;2use laravel::search::Searchable;34#[model(searchable)]5pub struct User {6 pub id: i64,7 #[search]8 pub name: String,9 #[search(prefix)]10 pub email: String,11 #[search(full_text)]12 pub bio: String,13}1415impl Searchable for User {}
Dedicated engines treat prefix and full_text the same as #[search], because they already handle tokenization, prefix matching, and full-text indexing automatically.
A full_text field requires a full-text index on PostgreSQL, MySQL, and MariaDB. Create it in the table's migration with table.full_text:
1table.text("body");2table.full_text(["body"]);1table.text("body");2table.full_text(["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 lt, le, gt, or ge (only eq, ne, is_in, and is_not_in).
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 order_by, latest, and oldest fail 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, pass index to searchable:
1#[model(searchable(index = "articles"))]2pub struct Post {3 // ...4}1#[model(searchable(index = "articles"))]2pub struct Post {3 // ...4}
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, implement indexed on Searchable. It receives the model's query and narrows it. Every search, sync, and import starts from the query it returns:
1use laravel::db::Builder;2use laravel::search::Searchable;34impl Searchable for Post {5 fn indexed(query: Builder<Self>) -> Builder<Self> {6 query.filter(Post::published.eq(true))7 }8}1use laravel::db::Builder;2use laravel::search::Searchable;34impl Searchable for Post {5 fn indexed(query: Builder<Self>) -> Builder<Self> {6 query.filter(Post::published.eq(true))7 }8}
Because indexed uses an ordinary model query, it supports any condition, including relationship conditions and eager loading with with. For example, a forum might only make threads with at least one reply searchable. A relationship's exists condition comes from the Relation trait, so import it in the model's file:
1use laravel::db::Builder;2use laravel::model::Relation;3use laravel::search::Searchable;45impl Searchable for Post {6 fn indexed(query: Builder<Self>) -> Builder<Self> {7 query.filter(Post::comments.exists())8 }9}1use laravel::db::Builder;2use laravel::model::Relation;3use laravel::search::Searchable;45impl Searchable for Post {6 fn indexed(query: Builder<Self>) -> Builder<Self> {7 query.filter(Post::comments.exists())8 }9}
Searching
Adding searchable to your model's #[model(searchable)] attribute gives the model a search method. Pass the search terms to Post::search and call get to retrieve the matching models, ranked by relevance by default. For example, this handler reads the q query parameter using a #[laravel::query] struct and returns the matching posts as JSON:
1use laravel::prelude::*;23use crate::models::Post;45#[laravel::query]6pub struct PostSearch {7 #[default]8 q: String,9}1011pub async fn index(12 Query(search): Query<PostSearch>,13) -> laravel::Result<Json<Vec<Post>>> {14 let posts = Post::search(&search.q).get().await?;1516 Ok(Json(posts))17}1use laravel::prelude::*;23use crate::models::Post;45#[laravel::query]6pub struct PostSearch {7 #[default]8 q: String,9}1011pub async fn index(12 Query(search): Query<PostSearch>,13) -> laravel::Result<Json<Vec<Post>>> {14 let posts = Post::search(&search.q).get().await?;1516 Ok(Json(posts))17}
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:
1let post = Post::search("rust").first().await?;23let posts = Post::search("rust").limit(5).get().await?;45let ids = Post::search("rust").keys().await?;1let post = Post::search("rust").first().await?;23let posts = Post::search("rust").limit(5).get().await?;45let ids = Post::search("rust").keys().await?;
first returns Option<Post>, which is None when no row matches.
Post::search returns a laravel::search::Query<Post>. If several handlers add the same filters to their searches, such as a public search page and an admin page that both search only published posts, you may write a function that takes and returns that type:
1use laravel::search::Query;23use crate::models::Post;45fn published(search: Query<Post>) -> Query<Post> {6 search.filter(Post::published.eq(true))7}1use laravel::search::Query;23use crate::models::Post;45fn published(search: Query<Post>) -> Query<Post> {6 search.filter(Post::published.eq(true))7}
Filtering and ordering
A search accepts the same filter conditions as a model query. For example, a blog's search box might restrict results to published posts:
1let posts = Post::search(terms)2 .filter(Post::published.eq(true))3 .get()4 .await?;1let posts = Post::search(terms)2 .filter(Post::published.eq(true))3 .get()4 .await?;
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 order_by, latest, or oldest:
1let posts = Post::search(terms)2 .filter(Post::published.eq(true))3 .latest(Post::created_at)4 .get()5 .await?;1let posts = Post::search(terms)2 .filter(Post::published.eq(true))3 .latest(Post::created_at)4 .get()5 .await?;
Some filters apply only when the reader asks for them, such as a category picked from a dropdown beside the search box. Instead of building the search in several steps, pass the optional value to when_some. Laravel applies the filter only when the value is Some, and passes it the value inside. If Post has a category field marked #[search(filterable)], a handler might filter on the category query parameter only when the request has one:
1use laravel::prelude::*;23use crate::models::Post;45#[laravel::query]6pub struct PostSearch {7 #[default]8 q: String,9 category: Option<String>,10}1112pub async fn index(13 Query(search): Query<PostSearch>,14) -> laravel::Result<Json<Vec<Post>>> {15 let posts = Post::search(&search.q)16 .when_some(search.category, |query, category| {17 query.filter(Post::category.eq(category))18 })19 .get()20 .await?;2122 Ok(Json(posts))23}1use laravel::prelude::*;23use crate::models::Post;45#[laravel::query]6pub struct PostSearch {7 #[default]8 q: String,9 category: Option<String>,10}1112pub async fn index(13 Query(search): Query<PostSearch>,14) -> laravel::Result<Json<Vec<Post>>> {15 let posts = Post::search(&search.q)16 .when_some(search.category, |query, category| {17 query.filter(Post::category.eq(category))18 })19 .get()20 .await?;2122 Ok(Json(posts))23}
when does the same for a bool, such as .when(only_published, |search| search.filter(Post::published.eq(true))).
Each filter compares one field with a value, using eq, ne, lt, le, gt, or ge, or with a list of values, using is_in or is_not_in. Every match must pass each filter you add. To match any of several values of one field, such as posts in either of two categories, use is_in:
1let posts = Post::search(terms)2 .filter(Post::published.eq(true))3 .filter(Post::category.is_in(["go", "rust"]))4 .get()5 .await?;1let posts = Post::search(terms)2 .filter(Post::published.eq(true))3 .filter(Post::category.is_in(["go", "rust"]))4 .get()5 .await?;
Filters must target a field marked filterable or the model's primary key, and ordering must target a field marked sortable or the primary key.
Compound conditions (&, |, !) and SQL-only conditions (like, relationship has, db::raw!) aren't supported on search queries. Put SQL-only constraints in indexed instead.
Loading relationships
When your results need related models, such as each post's author, call with. It eager-loads the relationships onto the returned models as a model query's with does:
1let posts = Post::search(terms)2 .with(Post::author)3 .get()4 .await?;1let posts = Post::search(terms)2 .with(Post::author)3 .get()4 .await?;
To eager-load a relationship on every search of the model, call with inside indexed.
Pagination
To paginate search results, call paginate or simple_paginate. Both return the same paginators as a model query, and their page links keep the request's entire query string, so page 2 of /posts?q=rust links to /posts?q=rust&page=2:
1use laravel::pagination::Paginator;2use laravel::prelude::*;34use crate::models::Post;56#[laravel::query]7pub struct PostSearch {8 #[default]9 q: String,10}1112pub async fn index(13 Query(search): Query<PostSearch>,14) -> laravel::Result<Json<Paginator<Post>>> {15 let posts = Post::search(&search.q)16 .filter(Post::published.eq(true))17 .paginate(15)18 .await?;1920 Ok(Json(posts))21}1use laravel::pagination::Paginator;2use laravel::prelude::*;34use crate::models::Post;56#[laravel::query]7pub struct PostSearch {8 #[default]9 q: String,10}1112pub async fn index(13 Query(search): Query<PostSearch>,14) -> laravel::Result<Json<Paginator<Post>>> {15 let posts = Post::search(&search.q)16 .filter(Post::published.eq(true))17 .paginate(15)18 .await?;1920 Ok(Json(posts))21}
paginate counts every matching row so it can display the total number of pages. If you only need previous and next links, call simple_paginate to skip the count.
Engine options
Each search service offers settings that Laravel doesn't wrap, such as Meilisearch's matchingStrategy or Typesense's num_typos. Pass them to options as JSON, and Laravel merges them into the outgoing request. The database engine sends no request, so a search with options or raw fails there:
1use serde_json::json;23let posts = Post::search(terms)4 .options(json!({ "matchingStrategy": "all" }))5 .get()6 .await?;1use serde_json::json;23let posts = Post::search(terms)4 .options(json!({ "matchingStrategy": "all" }))5 .get()6 .await?;
When you need more of the engine's response than the loaded models, such as Meilisearch's highlighted snippets, call raw instead of get. It returns the engine's full JSON response as a serde_json::Value. By default, Laravel asks Meilisearch and Typesense only for each document's primary key, so pass attributesToRetrieve on Meilisearch (or include_fields on Typesense) when you want additional fields in the raw response:
1use serde_json::json;23let response = Post::search(terms)4 .options(json!({5 "attributesToRetrieve": ["id", "title"],6 "attributesToHighlight": ["title"],7 }))8 .raw()9 .await?;1011if let Some(hits) = response["hits"].as_array() {12 for hit in hits {13 let id = hit["id"].as_i64();14 let highlighted = hit["_formatted"]["title"].as_str();15 // ...16 }17}1use serde_json::json;23let response = Post::search(terms)4 .options(json!({5 "attributesToRetrieve": ["id", "title"],6 "attributesToHighlight": ["title"],7 }))8 .raw()9 .await?;1011if let Some(hits) = response["hits"].as_array() {12 for hit in hits {13 let id = hit["id"].as_i64();14 let highlighted = hit["_formatted"]["title"].as_str();15 // ...16 }17}
Any option with the same name as a parameter Laravel sends replaces Laravel's value. For example, passing Meilisearch's filter replaces Laravel's generated filters, and passing limit overrides Laravel's pagination size.
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 user_id marked filterable:
1let filter = format!(2 "team_id = {} AND (shared = true OR user_id = {})",3 user.team_id, user.id4);56let posts = Post::search(terms)7 .options(json!({ "filter": filter }))8 .get()9 .await?;1let filter = format!(2 "team_id = {} AND (shared = true OR user_id = {})",3 user.team_id, user.id4);56let posts = Post::search(terms)7 .options(json!({ "filter": filter }))8 .get()9 .await?;
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, declare its embeddings in #[model(..)] with the number of dimensions your embedding model produces, such as 1,536 for OpenAI's text-embedding-3-small:
1use laravel::model::model;2use laravel::search::Searchable;34#[model(searchable(embedding(dimensions = 1536)))]5pub struct Post {6 pub id: i64,7 #[search(weight = 3)]8 pub title: String,9 #[search(full_text)]10 pub body: String,11}1213impl Searchable for Post {}1use laravel::model::model;2use laravel::search::Searchable;34#[model(searchable(embedding(dimensions = 1536)))]5pub struct Post {6 pub id: i64,7 #[search(weight = 3)]8 pub title: String,9 #[search(full_text)]10 pub body: String,11}1213impl Searchable for Post {}
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 addingembedding(...), 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:
1table.vector("embedding", 1536).nullable();1table.vector("embedding", 1536).nullable();
On PostgreSQL, you may chain .index() 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:
1table.vector("embedding", 1536).nullable().index();1table.vector("embedding", 1536).nullable().index();
Registering an embedder
Laravel doesn't call an embedding provider itself, so register an embedder function with app.search().embed_with in src/app.rs. Your embedder receives a Vec<String> and returns one laravel::db::Vector per input text in the same order:
1// src/app.rs2use laravel::db::Vector;34Application::configure()5 .with_services(|app| {6 app.search().embed_with(|texts: Vec<String>| async move {7 // Generate embeddings with OpenAI or another provider...8 Ok(Vec::<Vector>::new())9 });10 })11 // ...1// src/app.rs2use laravel::db::Vector;34Application::configure()5 .with_services(|app| {6 app.search().embed_with(|texts: Vec<String>| async move {7 // Generate embeddings with OpenAI or another provider...8 Ok(Vec::<Vector>::new())9 });10 })11 // ...
Once registered, Laravel embeds a model whenever it syncs (up to 100 rows per call). On the database engine, Laravel still embeds models after create! and after updates to marked 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 marked for search (#[search], prefix, full_text, or weight), joined with blank lines. Unmarked 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), implement embedding_input. Because Laravel can't tell which columns embedding_input reads, returning Some syncs on every update unless you also override needs_reindex:
1use laravel::search::Searchable;23impl Searchable for Post {4 fn embedding_input(&self) -> Option<String> {5 Some(self.title.clone())6 }7}1use laravel::search::Searchable;23impl Searchable for Post {4 fn embedding_input(&self) -> Option<String> {5 Some(self.title.clone())6 }7}
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:
1let posts = Post::search("pasta recipes")2 .semantic()3 .limit(10)4 .get()5 .await?;1let posts = Post::search("pasta recipes")2 .semantic()3 .limit(10)4 .get()5 .await?;
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, with no cutoff. Pass min_similarity to set the cutoff yourself:
1let posts = Post::search(terms)2 .semantic()3 .min_similarity(0.5)4 .paginate(15)5 .await?;1let posts = Post::search(terms)2 .semantic()3 .min_similarity(0.5)4 .paginate(15)5 .await?;
On Meilisearch, min_similarity 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. Turbopuffer has no similarity cutoff, so min_similarity fails there.
Because each embedding model distributes cosine similarity scores differently, you may need to tune min_similarity against your own data by testing a few sample queries and raising the threshold where irrelevant results begin.
Filters, with, limit, and pagination work as they do in a text search. Because similarity determines the order, a semantic search with order_by, latest, or oldest fails with an error naming the conflict. A semantic or hybrid search with blank terms also fails, because there is no meaning to compare, 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:
1let posts = Post::search(terms).hybrid().paginate(15).await?;1let posts = Post::search(terms).hybrid().paginate(15).await?;
Text and semantic rankings carry equal weight by default (1.0 and 1.0). To emphasize one over the other, call weights with the text weight followed by the semantic weight. The numbers are relative: passing 1.0 and 2.0 gives semantic meaning twice as much influence as text matching, which works well in a help center where readers rarely guess your exact terminology:
1let posts = Post::search(terms)2 .hybrid()3 .weights(1.0, 2.0)4 .paginate(15)5 .await?;1let posts = Post::search(terms)2 .hybrid()3 .weights(1.0, 2.0)4 .paginate(15)5 .await?;
min_similarity 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 the standard #[model(searchable)] attribute and text marks, with no embedding(...) declaration and no embed_with callback:
1use laravel::model::model;2use laravel::search::Searchable;34#[model(searchable)]5pub struct Post {6 pub id: i64,7 #[search(weight = 3)]8 pub title: String,9 #[search]10 pub body: String,11}1213impl Searchable for Post {}1use laravel::model::model;2use laravel::search::Searchable;34#[model(searchable)]5pub struct Post {6 pub id: i64,7 #[search(weight = 3)]8 pub title: String,9 #[search]10 pub body: String,11}1213impl Searchable for Post {}
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:
1TYPESENSE_EMBEDDING_MODEL=ts/all-MiniLM-L12-v21TYPESENSE_EMBEDDING_MODEL=ts/all-MiniLM-L12-v2
Turbopuffer
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:
1TURBOPUFFER_EMBEDDING_MODEL=openai/text-embedding-3-small1TURBOPUFFER_EMBEDDING_MODEL=openai/text-embedding-3-small
Because 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 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:
1MEILISEARCH_EMBEDDING_SOURCE=huggingFace2MEILISEARCH_EMBEDDING_MODEL=BAAI/bge-small-en-v1.51MEILISEARCH_EMBEDDING_SOURCE=huggingFace2MEILISEARCH_EMBEDDING_MODEL=BAAI/bge-small-en-v1.5
1MEILISEARCH_EMBEDDING_SOURCE=openAi2MEILISEARCH_EMBEDDING_MODEL=text-embedding-3-small3MEILISEARCH_EMBEDDING_API_KEY=sk-...1MEILISEARCH_EMBEDDING_SOURCE=openAi2MEILISEARCH_EMBEDDING_MODEL=text-embedding-3-small3MEILISEARCH_EMBEDDING_API_KEY=sk-...
Because 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 marked text fields, joined with blank lines.
If you later change the source, model, or marked 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 in each index's settings yourself (such as one with a custom documentTemplate, as Meilisearch's AI-powered search guide describes), set MEILISEARCH_EMBEDDER to its name instead. Laravel then searches with that embedder without modifying its settings:
1MEILISEARCH_EMBEDDER=posts1MEILISEARCH_EMBEDDER=posts
Keeping the index in sync
Whenever your application calls create!, update!, delete, or destroy 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 the write completes.
Each sync re-reads the row through indexed. If indexed still returns the row, Laravel sends its marked fields to the index. If it doesn't, such as when a post is unpublished or deleted, Laravel removes the row from the index.
An update syncs only when it changes a marked field or the primary key, so updating an unmarked column such as a view count skips syncing. A model that defines indexed or embedding_input syncs on every update because Laravel can't tell which columns those methods inspect. To control which column changes trigger a sync instead, override needs_reindex:
1use laravel::model::Changes;2use laravel::search::Searchable;34impl Searchable for Post {5 fn needs_reindex(&self, changes: &Changes<Self>) -> bool {6 changes.has(Post::title) || changes.has(Post::author_id)7 }8}1use laravel::model::Changes;2use laravel::search::Searchable;34impl Searchable for Post {5 fn needs_reindex(&self, changes: &Changes<Self>) -> bool {6 changes.has(Post::title) || changes.has(Post::author_id)7 }8}
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. Instead of failing the write, Laravel reports the sync error with the model name and key, and create!, update!, delete, or the surrounding transaction returns as usual. For automatic retries during brief outages, enable queued syncs. Once the service recovers, pass the affected rows to search::sync or run search:import to resync the table. Because you call search::sync directly, it returns sync errors to the caller.
The database engine queries the table directly and has no separate index to sync, except for the embeddings of a model that declares them.
Queueing syncs
By default, Laravel syncs the index before the model write returns. In production, set SEARCH_QUEUE=true so syncs run on your queue and a slow search service never delays web requests:
1SEARCH_QUEUE=true1SEARCH_QUEUE=true
When an editor saves a post several times in a minute, the index only needs the final version. Laravel debounces single-row syncs so the job waits 5 seconds for further edits (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 syncing `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 for a second, 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, create a src/config/search.rs configuration file and register it in src/config/mod.rs:
1// src/config/search.rs2use laravel::config::search::Search;3use laravel::config::{self, Env};4use laravel::time::ToSpan;56#[config::section]7fn search(env: &Env) -> Search {8 Search {9 debounce_for: 10.seconds().into(),10 max_wait: 2.minutes().into(),11 ..Search::from_env(env)12 }13}1// src/config/search.rs2use laravel::config::search::Search;3use laravel::config::{self, Env};4use laravel::time::ToSpan;56#[config::section]7fn search(env: &Env) -> Search {8 Search {9 debounce_for: 10.seconds().into(),10 max_wait: 2.minutes().into(),11 ..Search::from_env(env)12 }13}
Writes that skip model events
Bulk query operations such as Post::query().filter(..).update(), insert, and upsert don't dispatch model events, so Laravel doesn't sync them automatically. After running a bulk write, pass the same query to search::sync:
1use laravel::search;23Post::query()4 .filter(Post::author_id.eq(author.id))5 .update()6 .published(false)7 .await?;89search::sync(Post::query().filter(Post::author_id.eq(author.id))).await?;1use laravel::search;23Post::query()4 .filter(Post::author_id.eq(author.id))5 .update()6 .published(false)7 .await?;89search::sync(Post::query().filter(Post::author_id.eq(author.id))).await?;
search::sync accepts a model query, a single model such as &post, or a list of models. It extracts their primary keys, re-queries the database through indexed in chunks of 500, upserts the rows that still match, and removes any keys that no longer exist or no longer match indexed. When SEARCH_QUEUE=true, it dispatches one queued job per 500 rows without debouncing.
When you already have the IDs of records to remove, Post::destroy(ids).await? deletes them and syncs the index automatically. For a query-based bulk delete, search::sync can't see rows that were already deleted, so load the posts first, run the delete, and pass them to search::sync to remove them from the index:
1use laravel::search;23let posts = Post::query().filter(Post::author_id.eq(author.id));4let deleted = posts.get().await?;56posts.delete().await?;78search::sync(&deleted).await?;1use laravel::search;23let posts = Post::query().filter(Post::author_id.eq(author.id));4let deleted = posts.get().await?;56posts.delete().await?;78search::sync(&deleted).await?;
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, wrap the writes in search::without_syncing:
1use laravel::search;23search::without_syncing(async || {4 // Create the posts...5 Ok(())6})7.await?;1use laravel::search;23search::without_syncing(async || {4 // Create the posts...5 Ok(())6})7.await?;
Other model event listeners continue to run inside without_syncing. Calling search::sync explicitly inside the closure still syncs the rows you pass to it. Writes performed inside a database transaction do not sync even after the transaction commits, whether without_syncing wraps the transaction or runs inside it.
After a seeder that pauses syncing, or one that inserts rows with a bulk insert, run search:import so the index holds the new posts:
1laravel db:seed2laravel search:import Post1laravel db:seed2laravel search:import Post
Importing and flushing
When you make an existing model searchable or change its marks, run search:import to upsert every row returned by indexed in chunks of 500, updating existing documents in place. When SEARCH_QUEUE=true, Laravel queues one job per 500 rows instead. Pass the model's struct name or index name (with or without SEARCH_PREFIX):
1laravel search:import Post1laravel search:import Post
To clear the index before importing (for example, to remove stale documents that no longer match indexed), pass --fresh. To remove every document from a model's index without re-importing, run search:flush:
1laravel search:import Post --fresh2laravel search:flush Post1laravel search:import Post --fresh2laravel search:flush Post
For a model that declares embeddings, 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 for your own type. An engine stores the documents Laravel sends and answers searches with the keys of matching rows. Laravel validates filters and orders against your marks before calling the engine, then loads the models for the returned keys:
1use laravel::search::{Document, Engine, Hits, Index, Search};2use serde_json::Value;34pub struct Algolia {5 pub app_id: String,6}78impl Engine for Algolia {9 async fn upsert(10 &self,11 index: &Index,12 documents: &[Document],13 ) -> laravel::Result<()> {14 // Send the documents to Algolia...15 todo!()16 }1718 async fn delete(&self, index: &Index, keys: &[Value]) -> laravel::Result<()> {19 // Remove the documents with these keys...20 todo!()21 }2223 async fn search(&self, index: &Index, search: &Search) -> laravel::Result<Hits> {24 // Search Algolia and return the keys it finds...25 todo!()26 }2728 async fn flush(&self, index: &Index) -> laravel::Result<()> {29 // Remove every document...30 todo!()31 }3233 async fn sync_index(&self, index: &Index) -> laravel::Result<()> {34 // Create the index when it's missing, and send its settings...35 todo!()36 }3738 async fn delete_index(&self, name: &str) -> laravel::Result<bool> {39 // Delete the index, returning whether it existed...40 todo!()41 }42}1use laravel::search::{Document, Engine, Hits, Index, Search};2use serde_json::Value;34pub struct Algolia {5 pub app_id: String,6}78impl Engine for Algolia {9 async fn upsert(10 &self,11 index: &Index,12 documents: &[Document],13 ) -> laravel::Result<()> {14 // Send the documents to Algolia...15 todo!()16 }1718 async fn delete(&self, index: &Index, keys: &[Value]) -> laravel::Result<()> {19 // Remove the documents with these keys...20 todo!()21 }2223 async fn search(&self, index: &Index, search: &Search) -> laravel::Result<Hits> {24 // Search Algolia and return the keys it finds...25 todo!()26 }2728 async fn flush(&self, index: &Index) -> laravel::Result<()> {29 // Remove every document...30 todo!()31 }3233 async fn sync_index(&self, index: &Index) -> laravel::Result<()> {34 // Create the index when it's missing, and send its settings...35 todo!()36 }3738 async fn delete_index(&self, name: &str) -> laravel::Result<bool> {39 // Delete the index, returning whether it existed...40 todo!()41 }42}
Next, select the engine in src/config/search.rs using EngineConfig::custom and attach your settings struct:
1// src/config/search.rs2use laravel::config::search::{EngineConfig, Search};3use laravel::config::{self, Env};45#[derive(Debug)]6pub struct AlgoliaSettings {7 pub app_id: String,8}910#[config::section]11fn search(env: &Env) -> Search {12 let settings = AlgoliaSettings {13 app_id: env.get("ALGOLIA_APP_ID").unwrap_or_default(),14 };1516 Search {17 engine: EngineConfig::custom("algolia").settings(settings).into(),18 ..Search::from_env(env)19 }20}1// src/config/search.rs2use laravel::config::search::{EngineConfig, Search};3use laravel::config::{self, Env};45#[derive(Debug)]6pub struct AlgoliaSettings {7 pub app_id: String,8}910#[config::section]11fn search(env: &Env) -> Search {12 let settings = AlgoliaSettings {13 app_id: env.get("ALGOLIA_APP_ID").unwrap_or_default(),14 };1516 Search {17 engine: EngineConfig::custom("algolia").settings(settings).into(),18 ..Search::from_env(env)19 }20}
Finally, register the engine factory under the same name in src/app.rs. Laravel invokes the factory on the first search or sync and passes your settings through definition.settings:
1// src/app.rs2Application::configure()3 .with_services(|app| {4 app.search().extend("algolia", async |_app, definition| {5 let settings = definition.settings::<AlgoliaSettings>()?;67 Ok(Algolia {8 app_id: settings.app_id.clone(),9 })10 });11 })1// src/app.rs2Application::configure()3 .with_services(|app| {4 app.search().extend("algolia", async |_app, definition| {5 let settings = definition.settings::<AlgoliaSettings>()?;67 Ok(Algolia {8 app_id: settings.app_id.clone(),9 })10 });11 })
A package may register a custom engine inside its service provider's register method instead. If SEARCH_ENGINE names an engine that no code registered, the application fails to start with an error naming it.
Testing
Most tests of searchable models should run on the database engine. New applications pin SEARCH_ENGINE=database in src/testing.rs, so your tests use it even when your .env selects Meilisearch for development. The database engine searches your test database directly, so a test that creates a post and searches for it needs no search service and no setup beyond your usual test database:
1use laravel::model::create;2use laravel::testing::prelude::*;34#[laravel::test]5async fn the_search_page_finds_published_posts(6 app: Application,7) -> laravel::Result<()> {8 create!(Post { title: "Rust tips", published: true }).await?;9 create!(Post { title: "Rust drafts", published: false }).await?;1011 app.get("/posts?q=rust")12 .await13 .assert_ok()14 .assert_json(json!({ "data": [{ "title": "Rust tips" }] }));1516 Ok(())17}1use laravel::model::create;2use laravel::testing::prelude::*;34#[laravel::test]5async fn the_search_page_finds_published_posts(6 app: Application,7) -> laravel::Result<()> {8 create!(Post { title: "Rust tips", published: true }).await?;9 create!(Post { title: "Rust drafts", published: false }).await?;1011 app.get("/posts?q=rust")12 .await13 .assert_ok()14 .assert_json(json!({ "data": [{ "title": "Rust tips" }] }));1516 Ok(())17}
A model that declares its embeddings calls your embedder each time it syncs, even on the database engine, so these tests would call your embedding provider. When a test doesn't care about search, such as a test of a post's edit form, run it on the discard engine instead. The discard engine indexes nothing, finds nothing, and never calls your embedder. To use it for every test, change the SEARCH_ENGINE override in src/testing.rs:
1// src/testing.rs2.with_envs([3 // ...4 ("SEARCH_ENGINE", "discard"),5])1// src/testing.rs2.with_envs([3 // ...4 ("SEARCH_ENGINE", "discard"),5])
Testing against a dedicated engine
Engine-specific behavior, such as Typesense's typo tolerance, only shows up against the real service. Keep those tests in a separate file such as tests/search_engines.rs and mark them #[ignore]. Override SEARCH_ENGINE with with_envs and set a dedicated SEARCH_PREFIX (such as test_blog_) so deleting the test index never touches your development indexes:
1// tests/search_engines.rs2use laravel::model::create;3use laravel::testing::prelude::*;45fn app_on_typesense() -> Application {6 app::testing::configure()7 .with_envs([8 ("SEARCH_ENGINE", "typesense"),9 ("SEARCH_PREFIX", "test_blog_"),10 ])11 .create()12}1314#[laravel::test(app = app_on_typesense)]15#[ignore = "needs Typesense"]16async fn typesense_tolerates_typos(app: Application) -> laravel::Result<()> {17 app.command("search:index Post").await.assert_successful();18 let post = create!(Post { title: "Carbonara at home" }).await?;1920 let found = Post::search("carbonra").keys().await;21 app.command("search:delete-index Post").await.assert_successful();2223 assert_eq!(found?, [post.id]);2425 Ok(())26}1// tests/search_engines.rs2use laravel::model::create;3use laravel::testing::prelude::*;45fn app_on_typesense() -> Application {6 app::testing::configure()7 .with_envs([8 ("SEARCH_ENGINE", "typesense"),9 ("SEARCH_PREFIX", "test_blog_"),10 ])11 .create()12}1314#[laravel::test(app = app_on_typesense)]15#[ignore = "needs Typesense"]16async fn typesense_tolerates_typos(app: Application) -> laravel::Result<()> {17 app.command("search:index Post").await.assert_successful();18 let post = create!(Post { title: "Carbonara at home" }).await?;1920 let found = Post::search("carbonra").keys().await;21 app.command("search:delete-index Post").await.assert_successful();2223 assert_eq!(found?, [post.id]);2425 Ok(())26}
To run only this group, pass --ignored, and add --test search_engines to run only the tests in that file:
1cargo test -- --ignored23cargo test --test search_engines -- --ignored1cargo test -- --ignored23cargo test --test search_engines -- --ignored
On MySQL and MariaDB, a full-text search can't see rows written inside an uncommitted transaction. Because tests using refresh_database roll back without committing, a test on MySQL or MariaDB doesn't find full_text matches. Test them on PostgreSQL.