LaraflareDocsFrameworkPackagesReleases13.x

Docs / Packages / Scout

Scout

Introduction

Scout (@laraflare/scout) provides a simple, driver-based solution for adding full-text search to your Eloquent models. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records.

Scout ships with a built-in database engine that uses MySQL / PostgreSQL full-text indexes and LIKE clauses to search your existing database — no external service required. For most applications, this is all you need. For an overview of all search options available in laraflare, consult the search documentation.

Scout also includes drivers for Algolia, Meilisearch, Typesense, and Turbopuffer when you need features like typo tolerance, faceted filtering, vector search, or geo-search at massive scale. A "vectorize" driver keeps your models in a Cloudflare Vectorize index, a "collection" driver is available for local development, and you are free to write custom engines as well.

Installation

First, install Scout using npm:

npm install @laraflare/scout

After installing Scout, you should publish the Scout configuration file using the vendor:publish Artisan command. This command will publish the scout.ts configuration file to your application's config directory:

npx artisan vendor:publish --provider="ScoutServiceProvider"

Finally, wrap the model you would like to make searchable with the Searchable mixin. The mixin will register a model observer that will automatically keep the model in sync with your search driver:

import { Model } from '@laraflare/framework';
import { Searchable } from '@laraflare/scout';

export class Post extends Searchable(Model) {
  //
}

Queueing

When using an engine that is not the database or collection engine, you should strongly consider configuring a queue driver before using the library. Running a queue worker will allow Scout to queue all operations that sync your model information to your search indexes, providing much better response times for your application's web interface.

Once you have configured a queue driver, set the value of the queue option in your config/scout.ts configuration file to true:

queue: true,

Even when the queue option is set to false, it's important to remember that some Scout drivers like Algolia and Meilisearch always index records asynchronously. In other words, even though the index operation has completed within your application, the search engine itself may not reflect the new and updated records immediately.

To specify the connection and queue that your Scout jobs utilize, you may define the queue configuration option as an object:

queue: {
  connection: 'redis',
  queue: 'scout',
},

Of course, if you customize the connection and queue that Scout jobs utilize, you should run a queue worker to process jobs on that connection and queue:

npx artisan queue:work redis --queue=scout

Unique Jobs

In write-heavy applications, you may wish to prevent Scout from queueing duplicate jobs for the same model records. You may opt into unique indexing jobs by registering the MakeSearchableUniquely and RemoveFromSearchUniquely job classes, typically within the boot method of a service provider:

import { Scout } from '@laraflare/scout';
import { MakeSearchableUniquely } from '@laraflare/scout/Jobs/MakeSearchableUniquely';
import { RemoveFromSearchUniquely } from '@laraflare/scout/Jobs/RemoveFromSearchUniquely';

Scout.makeSearchableUsing(MakeSearchableUniquely);
Scout.removeFromSearchUsing(RemoveFromSearchUniquely);

These jobs use unique job locks to avoid dispatching duplicate queued indexing operations for the same searchable model records while a matching job is already queued.

Driver Prerequisites

Algolia

When using the Algolia driver, you should configure your Algolia id and secret credentials in your config/scout.ts configuration file. The Algolia client is built into Scout, so there is nothing else to install.

Meilisearch

Meilisearch is a fast, open source search engine that supports full-text, semantic, and hybrid search. You can self-host Meilisearch or use Meilisearch Cloud.

The Meilisearch driver uses a Meilisearch client that your application binds in the service container; Scout throws an error asking for one when none is bound.

Then, set the SCOUT_DRIVER environment variable as well as your Meilisearch host and key credentials within your application's .env file:

SCOUT_DRIVER=meilisearch
MEILISEARCH_HOST=http://127.0.0.1:7700
MEILISEARCH_KEY=masterKey

For more information regarding Meilisearch, please consult the Meilisearch documentation.

Typesense

Typesense is a lightning-fast, open source search engine and supports keyword search, semantic search, geo search, and vector search.

You can self-host Typesense or use Typesense Cloud.

The Typesense driver uses a Typesense client that your application binds in the service container; Scout throws an error asking for one when none is bound.

Then, set the SCOUT_DRIVER environment variable as well as your Typesense host and API key credentials within your application's .env file:

SCOUT_DRIVER=typesense
TYPESENSE_API_KEY=masterKey
TYPESENSE_HOST=localhost

You may also optionally specify your installation's port, path, and protocol:

TYPESENSE_PORT=8108
TYPESENSE_PATH=
TYPESENSE_PROTOCOL=http

Additional settings and schema definitions for your Typesense collections can be found within your application's config/scout.ts configuration file. For more information regarding Typesense, please consult the Typesense documentation.

Turbopuffer

Turbopuffer is a search engine that supports full-text, semantic, and hybrid search. To use the Turbopuffer driver, set the SCOUT_DRIVER environment variable and provide your Turbopuffer API key:

SCOUT_DRIVER=turbopuffer
TURBOPUFFER_API_KEY=tpuf_...
TURBOPUFFER_REGION=gcp-us-central1

The TURBOPUFFER_REGION environment variable is optional and defaults to gcp-us-central1.

Vectorize

The vectorize driver keeps each searchable model as a vector in your Worker's Cloudflare Vectorize index and searches by similarity. Add the index to your Worker as a binding, then set the driver:

SCOUT_DRIVER=vectorize
VECTORIZE_BINDING=VECTORIZE

The vectorize entry of config/scout.ts holds the binding's name and topK, the number of matches a search asks for when it sets no limit.

Each model's searchable text, and each search query, is embedded with the AI SDK (install @laraflare/ai). By default it uses Workers AI through your Worker's AI binding and the @cf/baai/bge-base-en-v1.5 model, whose vectors have 768 dimensions, so create the index to match:

npx wrangler vectorize create posts --dimensions=768 --metric=cosine
[ai]
binding = "AI"

[[vectorize]]
binding = "VECTORIZE"
index_name = "posts"

To embed with another provider or model from your config/ai.ts, set them in the embedding settings, or with the VECTORIZE_EMBEDDING_PROVIDER and VECTORIZE_EMBEDDING_MODEL environment variables:

vectorize: {
  binding: env('VECTORIZE_BINDING', 'VECTORIZE'),
  topK: 10,
  embedding: {
    provider: env('VECTORIZE_EMBEDDING_PROVIDER', 'workers-ai'),
    model: env('VECTORIZE_EMBEDDING_MODEL'),
    dimensions: null,
  },
},

The embeddings are cached as the AI SDK's embeddings caching is configured. Without the embedding settings, the engine uses the provider registered with useEmbeddings().

Configuration

Configuring Searchable Data

By default, the entire toArray form of a given model will be persisted to its search index. If you would like to customize the data that is synchronized to the search index, you may override the toSearchableArray method on the model:

import { Model } from '@laraflare/framework';
import { Searchable } from '@laraflare/scout';

export class Post extends Searchable(Model) {
  /**
   * Get the indexable data array for the model.
   */
  toSearchableArray(): Record<string, unknown> {
    const array = this.toArray();

    // Customize the data array...

    return array;
  }
}

Configuring Model Engines

When searching, Scout will typically use the default search engine specified in your application's scout configuration file. However, the search engine for a particular model can be changed by overriding the searchableUsing method on the model:

import { Model } from '@laraflare/framework';
import { Scout, Searchable } from '@laraflare/scout';
import type { Engine } from '@laraflare/scout/Engines/Engine';

export class User extends Searchable(Model) {
  /**
   * Get the engine used to index the model.
   */
  searchableUsing(): Engine {
    return Scout.engine('meilisearch');
  }
}

Database / Collection Engines

Database Engine

Warning

The database engine currently supports MySQL and PostgreSQL, both of which provide support for fast, full-text column indexing.

The database engine uses MySQL / PostgreSQL full-text indexes and LIKE clauses to search your existing database directly. For many applications, this is the simplest and most practical way to add search — no external service or additional infrastructure required.

To use the database engine, set the SCOUT_DRIVER environment variable to database:

SCOUT_DRIVER=database

Once configured, you may define your searchable data and start executing search queries against your models. Unlike third-party engines, the database engine requires no separate indexing step — it searches your database tables directly.

Semantic and Hybrid Search

The database engine supports semantic and hybrid search when using PostgreSQL with the pgvector extension. To get started, add a nullable vector column and a full-text index to your model's table. The vector column must be nullable because Scout stores the embedding after the model has been persisted:

await Schema.ensureVectorExtensionExists();

await Schema.table('articles', (table) => {
  // ...

  table.vector('embedding', 1536).nullable();
  table.vectorIndex('embedding');
  table.fullText(['title', 'body']);
});

Next, define a toSearchableEmbedding method on the model. This method may return the source text that Scout should embed or a precomputed embedding array. Scout stores embeddings in the embedding column by default; to use another column, define a searchableEmbeddingColumn method on the model.

Customizing Database Searching Strategies

By default, the database engine will execute a LIKE query against every model attribute that you have configured as searchable. However, you can assign more efficient search strategies to specific columns. The searchUsingFullText static property will use your database's full-text index for that column, while searchUsingPrefix will only match the beginning of strings (example%) instead of searching within the entire string (%example%).

To define this behavior, set these static properties on your model. Any columns without a setting will continue to use the default LIKE strategy:

export class User extends Searchable(Model) {
  static searchUsingPrefix = ['id', 'email'];

  static searchUsingFullText = ['bio'];

  /**
   * Get the indexable data array for the model.
   */
  toSearchableArray(): Record<string, unknown> {
    return {
      id: this.id,
      name: this.name,
      email: this.email,
      bio: this.bio,
    };
  }
}

Warning

Before specifying that a column should use full text query constraints, ensure that the column has been assigned a full text index.

PostgreSQL Full-Text Search

When using PostgreSQL, Scout can search stored tsvector columns for indexed, weighted full-text search. To get started, use the searchable method in a migration to add a generated search_vector column and its GIN index:

await Schema.table('posts', (table) => {
  table.searchable([['title', 'A'], ['body', 'D']]);
});

Column weights range from A (highest) to D (lowest). You may also pass a list of column names without weights, such as ['title', 'body'], to assign each column the default weight of D. PostgreSQL automatically updates the generated column when the source columns change.

Next, set the searchUsingFullText and fullTextOptions static properties on your model, setting the vector option to true:

export class Post extends Searchable(Model) {
  static searchUsingFullText = ['search_vector'];

  static fullTextOptions = { vector: true };

  /**
   * Get the indexable data array for the model.
   */
  toSearchableArray(): Record<string, unknown> {
    return { search_vector: null };
  }
}

Only the column name is needed; Scout searches the stored value directly. Return only the vector column to avoid adding LIKE clauses for other attributes, which can prevent PostgreSQL from using the GIN index.

The searchable method also accepts a text search configuration, columns for trigram indexes, and a custom vector column name, in that order:

table.searchable(
  [['title', 'A'], ['body', 'D']],
  'english', // language
  ['title'], // trigram
  'search_vector', // tsvector
);

To remove the generated column and its indexes when rolling back a migration, use the dropSearchable method, passing the same trigram columns and vector column name:

await Schema.table('posts', (table) => {
  table.dropSearchable(['title'], 'search_vector');
});

PostgreSQL Search Options

You may customize PostgreSQL full-text search using the fullTextOptions static property:

Option Description Default
vector Whether the full-text columns are stored tsvector columns. false
language The text search configuration, such as english or public.english_unaccent. english
mode The query syntax: plain, phrase, websearch, or raw. plain
rank The ranking function: ts_rank or ts_rank_cd. ts_rank
trigram A column name or array of columns for typo-tolerant matching. None
trigram_mode Whether trigram matching is used as a fallback or blended with full-text matches using blend. fallback

The plain mode searches for all query terms, while phrase matches terms in order. The websearch mode supports web search syntax, such as quoted phrases and excluded terms, and raw accepts PostgreSQL tsquery syntax. When searching a stored vector column, the language must match the text search configuration used to generate the column.

To enable typo tolerance, specify trigram columns in both the migration and the options:

static searchUsingFullText = ['search_vector'];

static fullTextOptions = { vector: true, trigram: ['title'] };

By default, Scout retries searches using trigram matching only when the initial search returns no results. Set trigram_mode to blend to include trigram matches alongside full-text matches and incorporate trigram similarity into relevance ranking.

Warning

Trigram matching requires the pg_trgm extension to be available on the connection's search path. When trigram columns are provided, the searchable migration method creates the extension, so the database user running migrations must have permission to create it.

You may override the mode, language, rank, trigram, and trigram_mode options for an individual search using the options method:

const posts = await Post.search('"laraflare scout"').options({ mode: 'websearch' }).get();

Collection Engine

The "collection" engine is intended for quick prototypes, extremely small datasets (a few hundred records), or running tests. It retrieves all possible records from your database and uses the Str.is helper to filter them in memory, so it does not require any indexing or database-specific features. For anything beyond trivial use cases, you should use the database engine instead.

To use the collection engine, you may simply set the value of the SCOUT_DRIVER environment variable to collection, or specify the collection driver directly in your application's scout configuration file:

SCOUT_DRIVER=collection

Once you have specified the collection driver as your preferred driver, you may start executing search queries against your models. Search engine indexing, such as the indexing needed to seed Algolia, Meilisearch, or Typesense indexes, is unnecessary when using the collection engine.

Differences From Database Engine

While the database engine uses full-text indexes and LIKE clauses to find matching records efficiently, the collection engine pulls all records and filters them in memory. The collection engine is the most portable option as it works across all relational databases supported by laraflare (including SQLite and SQL Server); however, it is significantly less efficient than the database engine and should not be used with large datasets.

Third-Party Engine Configuration

The following configuration options are only relevant when using a third-party search engine such as Algolia, Meilisearch, or Typesense. If you are using the database engine, you may skip this section.

Configuring Model Indexes

When using a third-party engine, each Eloquent model is synced with a given search "index", which contains all of the searchable records for that model. By default, each model will be persisted to an index matching the model's typical "table" name. Typically, this is the plural form of the model name; however, you are free to customize the model's index by overriding the searchableAs method on the model:

import { Model } from '@laraflare/framework';
import { Searchable } from '@laraflare/scout';

export class Post extends Searchable(Model) {
  /**
   * Get the name of the index associated with the model.
   */
  searchableAs(): string {
    return 'posts_index';
  }
}

Note

The searchableAs method has no effect when using the database engine, which always searches the model's database table directly.

Configuring the Model ID

By default, Scout will use the primary key of the model as the model's unique ID / key that is stored in the search index. If you need to customize this behavior when using a third-party engine, you may override the getScoutKey, getScoutKeyName, and getScoutKeyType methods on the model. The getScoutKeyType method tells Scout how to query for the models matching your search results, so it should return string when your custom key is not an integer:

import { Model } from '@laraflare/framework';
import { Searchable } from '@laraflare/scout';

export class User extends Searchable(Model) {
  /**
   * Get the value used to index the model.
   */
  getScoutKey(): unknown {
    return this.email;
  }

  /**
   * Get the key name used to index the model.
   */
  getScoutKeyName(): string {
    return 'email';
  }

  /**
   * Get the key type used to query the model.
   */
  getScoutKeyType(): string {
    return 'string';
  }
}

Algolia

Index Settings

Sometimes you may want to configure additional settings on your Algolia indexes. While you can manage these settings via the Algolia UI, it is sometimes more efficient to manage the desired state of your index configuration directly from your application's config/scout.ts configuration file.

This approach allows you to deploy these settings through your application's automated deployment pipeline, avoiding manual configuration and ensuring consistency across multiple environments. You may configure filterable attributes, ranking, faceting, or any other supported settings.

To get started, add settings for each index in your application's config/scout.ts configuration file:

algolia: {
  id: env('ALGOLIA_APP_ID', ''),
  secret: env('ALGOLIA_SECRET', ''),
  'index-settings': {
    users: {
      searchableAttributes: ['id', 'name', 'email'],
      attributesForFaceting: ['filterOnly(email)'],
      // Other settings fields...
    },
    flights: {
      searchableAttributes: ['id', 'destination'],
    },
  },
},

The keys of index-settings are the index names, which are the models' searchableAs values (the table names by default).

If the model underlying a given index is soft deletable and is included in the index-settings object, Scout will automatically include support for faceting on soft deleted models on that index. If you have no other faceting attributes to define for a soft deletable model index, you may simply add an empty entry to the index-settings object for that model:

'index-settings': {
  flights: {},
},

After configuring your application's index settings, you must invoke the scout:sync-index-settings Artisan command. This command will inform Algolia of your currently configured index settings. For convenience, you may wish to make this command part of your deployment process:

npx artisan scout:sync-index-settings

Identifying Users

Scout allows you to auto identify users when using Algolia. Associating the authenticated user with search operations may be helpful when viewing your search analytics within Algolia's dashboard. You can enable user identification by defining a SCOUT_IDENTIFY environment variable as true in your application's .env file:

SCOUT_IDENTIFY=true

Enabling this feature will also pass the request's IP address and your authenticated user's primary identifier to Algolia so this data is associated with any search request that is made by the user.

Meilisearch

Index Settings

Meilisearch requires you to pre-define index search settings such as filterable attributes, sortable attributes, and other supported settings fields.

Filterable attributes are any attributes you plan to filter on when invoking Scout's where method, while sortable attributes are any attributes you plan to sort by when invoking Scout's orderBy method. To define your index settings, adjust the index-settings portion of your meilisearch configuration entry in your application's scout configuration file:

meilisearch: {
  host: env('MEILISEARCH_HOST', 'http://localhost:7700'),
  key: env('MEILISEARCH_KEY'),
  'index-settings': {
    users: {
      filterableAttributes: ['id', 'name', 'email'],
      sortableAttributes: ['created_at'],
      // Other settings fields...
    },
    flights: {
      filterableAttributes: ['id', 'destination'],
      sortableAttributes: ['updated_at'],
    },
  },
},

If the model underlying a given index is soft deletable and is included in the index-settings object, Scout will automatically include support for filtering on soft deleted models on that index. If you have no other filterable or sortable attributes to define for a soft deletable model index, you may simply add an empty entry to the index-settings object for that model:

'index-settings': {
  flights: {},
},

After configuring your application's index settings, you must invoke the scout:sync-index-settings Artisan command. This command will inform Meilisearch of your currently configured index settings. For convenience, you may wish to make this command part of your deployment process:

npx artisan scout:sync-index-settings

Semantic and Hybrid Search

To use semantic or hybrid search with Meilisearch, configure an embedder in the index settings and embedding settings for each searchable model:

meilisearch: {
  // ...
  'index-settings': {
    articles: {
      embedders: {
        default: {
          source: 'userProvided',
          dimensions: 1536,
        },
      },
    },
  },
  'model-settings': {
    Article: {
      embedding: {
        embedder: 'default',
        dimensions: 1536,
      },
    },
  },
},

The model-settings keys are the model class names. The model's toSearchableEmbedding method may return source text, which Scout embeds using the AI SDK, or a precomputed embedding array. After updating the configuration, run the scout:sync-index-settings command.

Alternatively, you may use Meilisearch's native embeddings by setting the embedding driver to meilisearch. In this mode, Meilisearch generates document and query embeddings using the configured embedder, so the dimensions option and toSearchableEmbedding method are not required:

meilisearch: {
  'index-settings': {
    articles: {
      embedders: {
        default: {
          source: 'openAi',
          apiKey: env('OPENAI_API_KEY'),
          model: 'text-embedding-3-small',
          documentTemplate: 'An article titled {{ doc.title }}: {{ doc.body }}',
        },
      },
    },
  },
  'model-settings': {
    Article: {
      embedding: {
        embedder: 'default',
        driver: 'meilisearch',
      },
    },
  },
},

When using native embeddings, Scout will not generate or add vectors to indexed documents. You may still provide a precomputed query vector using the vector search option. As with other index settings, run the scout:sync-index-settings command after updating the embedder configuration.

For more information regarding the available embedder sources and their options, please consult the Meilisearch hybrid search documentation.

Searchable Data Types

Meilisearch will only perform filter operations (>, <, etc.) on data of the correct type. When customizing your searchable data, you should ensure that numeric values are cast to their correct type:

toSearchableArray(): Record<string, unknown> {
  return {
    id: Number(this.id),
    name: this.name,
    price: Number(this.price),
  };
}

Typesense

Preparing Searchable Data

When utilizing Typesense, your searchable models must define a toSearchableArray method that casts your model's primary key to a string and creation date to a UNIX timestamp:

/**
 * Get the indexable data array for the model.
 */
toSearchableArray(): Record<string, unknown> {
  return {
    ...this.toArray(),
    id: String(this.id),
    created_at: this.created_at.timestamp,
  };
}

You should also define your Typesense collection schemas in your application's config/scout.ts file. A collection schema describes the data types of each field that is searchable via Typesense. For more information on all available schema options, please consult the Typesense documentation.

If you need to change your Typesense collection's schema after it has been defined, you may either run scout:flush and scout:import, which will delete all existing indexed data and recreate the schema. Or, you may use Typesense's API to modify the collection's schema without removing any indexed data.

If your searchable model is soft deletable, you should define a __soft_deleted field in the model's corresponding Typesense schema within your application's config/scout.ts configuration file:

'model-settings': {
  User: {
    'collection-schema': {
      fields: [
        // ...
        {
          name: '__soft_deleted',
          type: 'int32',
          optional: true,
        },
      ],
    },
  },
},

Embeddings

To enable semantic and hybrid search, define an embedding setting and vector field in the model's Typesense configuration. By default, Scout uses the AI SDK to generate embeddings:

'model-settings': {
  Article: {
    'collection-schema': {
      fields: [
        { name: 'title', type: 'string' },
        { name: 'embedding', type: 'float[]', num_dim: 1536 },
      ],
    },
    'search-parameters': { query_by: 'title' },
    embedding: {
      attribute: 'embedding',
      dimensions: 1536,
    },
  },
},

Your model's toSearchableEmbedding method should return the source text that Scout should embed or a precomputed embedding array:

toSearchableEmbedding(): string | number[] {
  return `${this.title} ${this.body}`;
}

Dynamic Search Parameters

Typesense allows you to modify your search parameters dynamically when performing a search operation via the options method:

await Todo.search('Groceries').options({
  query_by: 'title, description',
}).get();

Turbopuffer

Turbopuffer requires a schema and searchable attributes for each model. Define them in the model-settings object of your turbopuffer configuration within the scout configuration file:

turbopuffer: {
  // ...
  'model-settings': {
    Article: {
      'searchable-attributes': {
        title: 3,
        body: 1,
      },
      schema: {
        title: { type: 'string', full_text_search: true },
        body: { type: 'string', full_text_search: true },
        status: { type: 'string' },
      },
    },
  },
},

The numeric values assigned to searchable-attributes are relative BM25 weights. In the example above, matches in the article title contribute three times the score of matches in the body.

To enable semantic and hybrid search, add an embedding setting and vector schema to the model's configuration:

turbopuffer: {
  // ...
  'model-settings': {
    Article: {
      'searchable-attributes': {
        title: 3,
        body: 1,
      },
      embedding: {
        attribute: 'embedding',
        dimensions: 1536,
      },
      schema: {
        title: { type: 'string', full_text_search: true },
        body: { type: 'string', full_text_search: true },
        embedding: { type: '[1536]f32', ann: true },
      },
    },
  },
},

Your model's toSearchableEmbedding method should return the source text that Scout should embed or a precomputed embedding array. Scout generates source-text embeddings using the AI SDK.

Alternatively, you may use Turbopuffer's native embeddings without defining a toSearchableEmbedding method. Set the embedding driver to turbopuffer and configure an embed schema on the searchable source attribute:

embedding: {
  driver: 'turbopuffer',
  attribute: 'embedding_text',
},

schema: {
  // ...
  embedding_text: {
    type: 'string',
    embed: {
      model: 'voyage/voyage-4',
      dimensions: 1024,
      attribute: 'embedding',
    },
  },
},

The source attribute must be included in the model's toSearchableArray output.

Third-Party Engine Indexing

Note

The indexing features described in this section are primarily relevant when using a third-party engine (Algolia, Meilisearch, Typesense, or Turbopuffer). The database engine searches your database tables directly, so it does not require manual index management.

Batch Import

If you are installing Scout into an existing project, you may already have database records you need to import into your indexes. Scout provides a scout:import Artisan command that you may use to import all of your existing records into your search indexes. The command takes the model's class name, as written in app/Models:

npx artisan scout:import "App\Models\Post"

The scout:queue-import command may be used to import all of your existing records using queued jobs:

npx artisan scout:queue-import "App\Models\Post" --chunk=500

The flush command may be used to remove all of a model's records from your search indexes:

npx artisan scout:flush "App\Models\Post"

Modifying the Import Query

If you would like to modify the query that is used to retrieve all of your models for batch importing, you may define a makeAllSearchableUsing method on your model. This is a great place to add any eager relationship loading that may be necessary before importing your models:

/**
 * Modify the query used to retrieve models when making all of the models searchable.
 */
protected makeAllSearchableUsing(query: any): any {
  return query.with('author');
}

Warning

When using a queue to batch import models, relationships eager loaded by the makeAllSearchableUsing method are retrieved again in their entirety when the job is processed, so any constraints applied to them are lost. If you need to constrain a relationship, eager load it in the makeSearchableUsing method instead, which runs within the job.

Adding Records

Once you have added the Searchable mixin to a model, all you need to do is save or create a model instance and it will automatically be added to your search index. If you have configured Scout to use queues this operation will be performed in the background by your queue worker:

const order = new Order();

// ...

await order.save();

Adding Records via Query

If you would like to add a collection of models to your search index via an Eloquent query, you may chain the searchable method onto the Eloquent query. The searchable method will chunk the results of the query and add the records to your search index. Again, if you have configured Scout to use queues, all of the chunks will be imported in the background by your queue workers:

await Order.where('price', '>', 100).searchable();

You may also call the searchable method on an Eloquent relationship instance:

await user.orders().searchable();

Or, if you already have a collection of Eloquent models in memory, you may call the searchable method on the collection instance to add the model instances to their corresponding index:

await orders.searchable();

Note

The searchable method can be considered an "upsert" operation. In other words, if the model record is already in your index, it will be updated. If it does not exist in the search index, it will be added to the index.

Updating Records

To update a searchable model, you only need to update the model instance's properties and save the model to your database. Scout will automatically persist the changes to your search index:

const order = await Order.find(1);

// Update the order...

await order.save();

You may also invoke the searchable method on an Eloquent query instance to update a collection of models. If the models do not exist in your search index, they will be created:

await Order.where('price', '>', 100).searchable();

If you would like to update the search index records for all of the models in a relationship, you may invoke the searchable on the relationship instance:

await user.orders().searchable();

Or, if you already have a collection of Eloquent models in memory, you may call the searchable method on the collection instance to update the model instances in their corresponding index:

await orders.searchable();

Modifying Records Before Importing

Sometimes you may need to prepare the collection of models before they are made searchable. For instance, you may want to eager load a relationship so that the relationship data can be efficiently added to your search index. To accomplish this, define a makeSearchableUsing method on the corresponding model:

import type { Collection } from '@laraflare/framework/Database/Eloquent/Collection';

/**
 * Modify the collection of models being made searchable.
 */
makeSearchableUsing(models: Collection<any>): Collection<any> {
  return models.load('author');
}

Conditionally Updating the Search Index

By default, Scout will reindex an updated model regardless of which attributes were modified. If you would like to customize this behavior, you may define a searchIndexShouldBeUpdated method on your model:

/**
 * Determine if the search index should be updated.
 */
searchIndexShouldBeUpdated(): boolean {
  return this.wasRecentlyCreated || this.wasChanged(['title', 'body']);
}

Removing Records

To remove a record from your index you may simply delete the model from the database. This may be done even if you are using soft deleted models:

const order = await Order.find(1);

await order.delete();

If you do not want to retrieve the model before deleting the record, you may use the unsearchable method on an Eloquent query instance:

await Order.where('price', '>', 100).unsearchable();

If you would like to remove the search index records for all of the models in a relationship, you may invoke the unsearchable on the relationship instance:

await user.orders().unsearchable();

Or, if you already have a collection of Eloquent models in memory, you may call the unsearchable method on the collection instance to remove the model instances from their corresponding index:

await orders.unsearchable();

To remove all of the model records from their corresponding index, you may invoke the removeAllFromSearch method:

await Order.removeAllFromSearch();

Pausing Indexing

Sometimes you may need to perform a batch of Eloquent operations on a model without syncing the model data to your search index. You may do this using the withoutSyncingToSearch method. This method accepts a single closure which will be immediately executed. Any model operations that occur within the closure will not be synced to the model's index:

await Order.withoutSyncingToSearch(async () => {
  // Perform model actions...
});

Conditionally Searchable Model Instances

Sometimes you may need to only make a model searchable under certain conditions. For example, imagine you have Post model that may be in one of two states: "draft" and "published". You may only want to allow "published" posts to be searchable. To accomplish this, you may define a shouldBeSearchable method on your model:

/**
 * Determine if the model should be searchable.
 */
shouldBeSearchable(): boolean {
  return this.isPublished();
}

The shouldBeSearchable method is only applied when manipulating models through the save and create methods, queries, or relationships. Directly making models or collections searchable using the searchable method will override the result of the shouldBeSearchable method.

Warning

The shouldBeSearchable method is not applicable when using Scout's "database" engine, as all searchable data is always stored in the database. To achieve similar behavior when using the database engine, you should use where clauses instead.

Searching

You may begin searching a model using the search method. The search method accepts a single string that will be used to search your models. You should then chain the get method onto the search query to retrieve the Eloquent models that match the given search query:

const orders = await Order.search('Star Trek').get();

Since Scout searches return a collection of Eloquent models, you may even return the results directly from a route or controller and they will automatically be converted to JSON:

import { Route } from '@laraflare/framework';

Route.get('/search', async (request) => {
  return await Order.search(request.input('search')).get();
});

If you would like to get the raw search results before they are converted to Eloquent models, you may use the raw method:

const orders = await Order.search('Star Trek').raw();

Semantic Search

The database, Meilisearch, Typesense, and Turbopuffer engines support semantic search, which matches records based on the meaning of a query. When Scout generates embeddings, semantic and hybrid searches require the AI SDK. Typesense's native embeddings, Turbopuffer's native embeddings, and precomputed query vectors do not require the AI SDK.

After configuring embeddings for the selected engine, invoke the semantic method on a search query:

const articles = await Article.search('staying cool in the summer')
  .semantic()
  .get();

You may provide a minimum similarity threshold when supported by the selected engine:

const articles = await Article.search('renewable energy storage')
  .semantic(0.6)
  .get();

To combine full-text and semantic search, use the hybrid method. Its first two arguments control the relative weights of text and semantic results:

const articles = await Article.search('renewable energy storage')
  .hybrid(1, 2)
  .get();

Custom Indexes

When searching using third-party engines, search queries will typically be performed on the index specified by the model's searchableAs method. However, you may use the within method to specify a custom index that should be searched instead:

const orders = await Order.search('Star Trek')
  .within('tv_shows_popularity_desc')
  .get();

Where Clauses

Scout allows you to add "where" clauses to your search queries. For example, basic equality checks are useful for scoping search queries by an owner ID:

const orders = await Order.search('Star Trek').where('user_id', 1).get();

You may also use the =, !=, <, >, >=, <= comparison operators to build more advanced queries:

await Order.search('Star Trek')
  .where('status', '=', 'completed')
  .where('is_refunded', '!=', true)
  .where('total_price', '>', 100)
  .where('shipping_cost', '<', 20)
  .where('discount_percent', '>=', 10)
  .where('item_count', '<=', 5)
  .get();

In addition, the whereIn method may be used to verify that a given column's value is contained within the given array:

const orders = await Order.search('Star Trek').whereIn(
  'status', ['open', 'paid'],
).get();

The whereNotIn method verifies that the given column's value is not contained in the given array:

const orders = await Order.search('Star Trek').whereNotIn(
  'status', ['closed'],
).get();

Warning

If your application is using Meilisearch, you must configure your application's filterable attributes before utilizing Scout's "where" clauses.

Customizing the Eloquent Results Query

After Scout retrieves a list of matching Eloquent models from your application's search engine, Eloquent is used to retrieve all of the matching models by their primary keys. You may customize this query by invoking the query method. The query method accepts a closure that will receive the Eloquent query builder instance as an argument:

const orders = await Order.search('Star Trek')
  .query((query) => query.with('invoices'))
  .get();

When using a third-party engine, this callback is invoked after the relevant models have already been retrieved from the search engine, so it should not be used for "filtering" results — use Scout where clauses instead. However, when using the database engine, the query method's constraints are applied directly to the database query, so you may use it for filtering as well.

Pagination

In addition to retrieving a collection of models, you may paginate your search results using the paginate method. This method will return a LengthAwarePaginator instance just as if you had paginated a traditional Eloquent query:

const orders = await Order.search('Star Trek').paginate();

You may specify how many models to retrieve per page by passing the amount as the first argument to the paginate method:

const orders = await Order.search('Star Trek').paginate(15);

When using the database engine, you may also use the simplePaginate method. Unlike paginate, which retrieves the total number of matching records so it can display page numbers, simplePaginate only determines whether there are more results beyond the current page — making it more efficient for large datasets where you only need "previous" and "next" links:

const orders = await Order.search('Star Trek').simplePaginate(15);

Once you have retrieved the results, you may return them from a route or controller to a Vue screen and render the page links there, just as if you had paginated a traditional Eloquent query. If you would like to retrieve the pagination results as JSON, you may return the paginator instance directly from a route or controller:

import { Route } from '@laraflare/framework';

Route.get('/orders', async (request) => {
  return await Order.search(request.input('query')).paginate(15);
});

Warning

Since search engines are not aware of your Eloquent model's global scope definitions, you should not utilize global scopes in applications that utilize Scout pagination. Or, you should recreate the global scope's constraints when searching via Scout.

Soft Deleting

If your indexed models are soft deleting and you need to search your soft deleted models, set the soft_delete option of the config/scout.ts configuration file to true:

soft_delete: true,

When this configuration option is true, Scout will not remove soft deleted models from the search index. Instead, it will set a hidden __soft_deleted attribute on the indexed record. Then, you may use the withTrashed or onlyTrashed methods to retrieve the soft deleted records when searching:

// Include trashed records when retrieving results...
const orders = await Order.search('Star Trek').withTrashed().get();

// Only include trashed records when retrieving results...
const orders = await Order.search('Star Trek').onlyTrashed().get();

Note

When a soft deleted model is permanently deleted using forceDelete, Scout will remove it from the search index automatically.

Customizing Engine Searches

If you need to perform advanced customization of the search behavior of an engine you may pass a closure as the second argument to the search method. For example, you could use this callback to add geo-location data to your search options before the search query is passed to Algolia:

await Order.search(
  'Star Trek',
  (algolia, query: string, options: Record<string, any>) => {
    options.aroundLatLng = '36,111';
    options.aroundRadius = 1000000;

    return algolia.search(query, options);
  },
).get();

Custom Engines

Writing the Engine

If one of the built-in Scout search engines doesn't fit your needs, you may write your own custom engine and register it with Scout. Your engine should extend the Engine abstract class. This abstract class contains the methods your custom engine must implement:

import type { Builder } from '@laraflare/scout/Builder';
import { Engine } from '@laraflare/scout/Engines/Engine';

abstract update(models: Collection<SearchableModel>): Promise<void>;
abstract delete(models: Collection<SearchableModel>): Promise<void>;
abstract search(builder: Builder): Promise<RawResults>;
abstract paginate(builder: Builder, perPage: number, page: number): Promise<RawResults>;
abstract mapIds(results: RawResults): Collection<unknown>;
abstract map(builder: Builder, results: RawResults, model: SearchableModel): Promise<Collection<SearchableModel>>;
abstract lazyMap(builder: Builder, results: RawResults, model: SearchableModel): Promise<LazyCollection<SearchableModel>>;
abstract getTotalCount(results: RawResults): number;
abstract flush(model: SearchableModel): Promise<void>;
abstract createIndex(name: string, options?: Record<string, unknown>): Promise<void>;
abstract deleteIndex(name: string): Promise<void>;

You may find it helpful to review the implementations of these methods on the Algolia4Engine class. This class will provide you with a good starting point for learning how to implement each of these methods in your own engine.

Registering the Engine

Once you have written your custom engine, you may register it with Scout using the extend method of the EngineManager. You should call the extend method from the boot method of your AppServiceProvider class or any other service provider used by your application:

import { EngineManager } from '@laraflare/scout/EngineManager';
import { MySqlSearchEngine } from '../ScoutExtensions/MySqlSearchEngine';

/**
 * Bootstrap any application services.
 */
boot(): void {
  EngineManager.extend('mysql', () => new MySqlSearchEngine());
}

Once your engine has been registered, you may specify it as your default Scout driver in your application's config/scout.ts configuration file:

driver: 'mysql',
Adapted from Laravel's documentation, Copyright (c) Taylor Otwell, used under the MIT License.