> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Search

> An overview of Laravel's search capabilities — full-text search, vector search, reranking, and Laravel Scout. Choose the right tool for each use case.

## Introduction

Almost every application needs search. Whether your users are searching a knowledge base for relevant articles, exploring a product catalog, or asking natural-language questions against a corpus of documents, Laravel provides built-in tools to handle each of these scenarios — and you often don't need any external services to get there.

```mermaid theme={null}
flowchart TD
    Q["Search requirement"]
    Q --> A{"Keyword matching enough?"}
    A -->|Yes| B["Full-Text Search<br>whereFullText"]
    A -->|No — match by meaning| C["Vector Search<br>whereVectorSimilarTo"]
    Q --> D{"Auto-sync model indexes?"}
    D -->|Yes| E["Laravel Scout<br>Searchable trait"]
    Q --> F{"Re-order results by AI relevance?"}
    F -->|Yes| G["Reranking<br>AI SDK Reranking"]
```

### Feature comparison

| Feature                | External service                  | Description                                              |
| ---------------------- | --------------------------------- | -------------------------------------------------------- |
| `whereFullText`        | None required                     | Native full-text indexes on MariaDB / MySQL / PostgreSQL |
| `whereVectorSimilarTo` | None (PostgreSQL + pgvector)      | Similarity search by meaning. Requires the AI SDK        |
| `Reranking`            | AI provider                       | Re-order any result set by semantic relevance            |
| Laravel Scout          | None (database engine) / optional | Automatic index sync for Eloquent models                 |

***

## Full-Text Search

While `LIKE` queries work well for simple substring matching, they don't understand language. Full-text search uses specialised indexes that understand word boundaries, stemming, and relevance scoring, so the database can return the most relevant results first.

Fast full-text search is built into MariaDB, MySQL, and PostgreSQL — no external search service is required.

<Warning>
  Full-text search is supported by MariaDB, MySQL, and PostgreSQL.
</Warning>

### Adding full-text indexes

To use full-text search, first add a full-text index to the columns you want to search. You may pass an array of columns to create a composite index that searches across multiple fields at once:

```php theme={null}
Schema::create('articles', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('body');
    $table->timestamps();

    $table->fullText(['title', 'body']); // composite index
});
```

On PostgreSQL you may specify a language configuration for the index, which controls how words are stemmed:

```php theme={null}
$table->fullText('body')->language('english');
```

For more information on creating indexes, consult the [migrations documentation](/en/migrations).

### Running full-text queries

Once the index is in place, use the `whereFullText` query builder method to search against it. Laravel generates the appropriate SQL for your database driver — `MATCH(...) AGAINST(...)` on MariaDB and MySQL, and `to_tsvector(...) @@ plainto_tsquery(...)` on PostgreSQL:

```php theme={null}
$articles = Article::whereFullText('body', 'web developer')->get();
```

When using a composite full-text index, pass the same array of columns to `whereFullText`:

```php theme={null}
$articles = Article::whereFullText(
    ['title', 'body'], 'web developer'
)->get();
```

<Info>
  On MariaDB and MySQL, results are automatically ordered by relevance score. On PostgreSQL, `whereFullText` filters matching records but does not order them by relevance. If you need automatic relevance ordering on PostgreSQL, consider using [Scout's database engine](#laravel-scout), which handles this for you.
</Info>

The `orWhereFullText` method adds a full-text search clause as an "or" condition. For complete details, consult the [query builder documentation](/en/query-builder).

***

## Semantic / Vector Search

Full-text search relies on keyword matching — the words in the query must appear in the data. Semantic search takes a fundamentally different approach: it uses AI-generated vector embeddings to represent the *meaning* of text as arrays of numbers, and then finds results whose meaning is closest to the query.

For example, a search for "best wineries in Napa Valley" can surface an article titled "Top Vineyards to Visit" — even though the words don't overlap at all.

<Note>
  Vector search requires the [Laravel AI SDK](/en/ai-sdk) and is supported by PostgreSQL (requires the `pgvector` extension) and MongoDB (requires the Laravel MongoDB package). All Postgres databases on [Laravel Cloud](https://laravel.com/cloud) already have `pgvector` installed.
</Note>

### Generating embeddings

An embedding is a high-dimensional numeric array that represents the semantic meaning of a piece of text. You may generate embeddings using the `toEmbeddings` method on Laravel's `Stringable` class:

```php theme={null}
use Illuminate\Support\Str;

$embedding = Str::of('Napa Valley has great wine.')->toEmbeddings();
```

To generate embeddings for multiple inputs at once — which requires only a single API call — use the `Embeddings` class:

```php theme={null}
use Laravel\Ai\Embeddings;

$response = Embeddings::for([
    'Napa Valley has great wine.',
    'Laravel is a PHP framework.',
])->generate();

$response->embeddings; // [[0.123, 0.456, ...], [0.789, 0.012, ...]]
```

For more details on configuring embedding providers and customising dimensions, consult the [AI SDK documentation](/en/ai-sdk).

### Storing and indexing vectors

Define a `vector` column in your migration, specifying the number of dimensions that matches your embedding provider's output (for example, 1536 for OpenAI's `text-embedding-3-small`). Call `index()` to create an HNSW index, which dramatically speeds up similarity searches on large datasets:

```php theme={null}
Schema::ensureVectorExtensionExists(); // enable the pgvector extension

Schema::create('documents', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->vector('embedding', dimensions: 1536)->index();
    $table->timestamps();
});
```

On your Eloquent model, cast the vector column to `array` so that Laravel automatically handles conversion between PHP arrays and the database's vector format:

```php theme={null}
protected function casts(): array
{
    return [
        'embedding' => 'array',
    ];
}
```

### Querying by similarity

Once you have stored embeddings, use `whereVectorSimilarTo` to find similar records. This method compares the given embedding against stored vectors using cosine similarity, filters out results below the `minSimilarity` threshold, and orders results by relevance. The threshold is a value between `0.0` and `1.0`, where `1.0` means the vectors are identical:

```php theme={null}
$documents = Document::query()
    ->whereVectorSimilarTo('embedding', $queryEmbedding, minSimilarity: 0.4)
    ->limit(10)
    ->get();
```

As a convenience, when a plain string is given instead of an embedding array, Laravel will automatically generate the embedding for you. This means you can pass the user's search query directly:

```php theme={null}
$documents = Document::query()
    ->whereVectorSimilarTo('embedding', 'best wineries in Napa Valley')
    ->limit(10)
    ->get();
```

For lower-level control, the `whereVectorDistanceLessThan`, `selectVectorDistance`, and `orderByVectorDistance` methods are also available. For complete details, consult the [query builder documentation](/en/query-builder) and the [AI SDK documentation](/en/ai-sdk).

***

## Reranking

Reranking is a technique where an AI model reorders a set of results by how semantically relevant each result is to a given query. Unlike vector search, which requires pre-computed stored embeddings, reranking works on any collection of text — it takes raw content and a query as input and returns the items sorted by relevance.

Reranking is especially powerful as a second stage after a fast initial retrieval step. Use full-text search to quickly narrow thousands of records down to the top 50 candidates, then use reranking to put the most relevant results at the top. This "retrieve then rerank" pattern gives you both speed and semantic accuracy.

```php theme={null}
use Laravel\Ai\Reranking;

$response = Reranking::of([
    'Django is a Python web framework.',
    'Laravel is a PHP web application framework.',
    'React is a JavaScript library for building user interfaces.',
])->rerank('PHP frameworks');

$response->first()->document; // "Laravel is a PHP web application framework."
```

Laravel collections also have a `rerank` macro that accepts a field name (or closure) and a query, making it easy to rerank Eloquent results:

```php theme={null}
$articles = Article::all()
    ->rerank('body', 'Laravel tutorials');
```

For complete details on configuring reranking providers and available options, consult the [AI SDK documentation](/en/ai-sdk).

***

## Laravel Scout

The search techniques described above are all query builder methods that you call directly in your code. [Laravel Scout](/en/scout) takes a different approach: it provides a `Searchable` trait that you add to your Eloquent models, and Scout automatically keeps your search indexes in sync as records are created, updated, and deleted.

### Database engine

Scout's built-in database engine performs full-text and `LIKE` searches against your existing database — no external service or extra infrastructure required. Add the `Searchable` trait to your model and define a `toSearchableArray` method that returns the columns you want to be searchable.

You may use PHP attributes to control the search strategy for each column:

```php theme={null}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Attributes\SearchUsingFullText;
use Laravel\Scout\Attributes\SearchUsingPrefix;
use Laravel\Scout\Searchable;

class Article extends Model
{
    use Searchable;

    #[SearchUsingPrefix(['id'])]
    #[SearchUsingFullText(['title', 'body'])]
    public function toSearchableArray(): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'body' => $this->body,
        ];
    }
}
```

| Attribute             | Search strategy                                                         |
| --------------------- | ----------------------------------------------------------------------- |
| `SearchUsingFullText` | Uses the database's full-text index (`MATCH...AGAINST` / `to_tsvector`) |
| `SearchUsingPrefix`   | Prefix match (`example%`)                                               |
| None                  | Wildcard on both sides (`%example%`)                                    |

<Warning>
  Before specifying that a column should use full-text query constraints, ensure that the column has been assigned a [full-text index](/en/migrations).
</Warning>

Once the trait is added, search your model using Scout's `search` method. Scout's database engine automatically orders results by relevance, even on PostgreSQL:

```php theme={null}
$articles = Article::search('Laravel')->get();
```

### Third-party engines

Scout also supports third-party search engines such as [Algolia](https://www.algolia.com/), [Meilisearch](https://www.meilisearch.com), and [Typesense](https://typesense.org). These dedicated search services offer advanced features like typo tolerance, faceted filtering, geo-search, and custom ranking rules.

Since Scout provides a unified API across all of its drivers, switching from the database engine to a third-party engine requires minimal code changes.

<Note>
  Many applications never need an external search engine. The built-in techniques described on this page cover the vast majority of use cases.
</Note>

For complete details on configuring Scout and third-party engines, consult the [Laravel Scout guide](/en/scout).

***

## Combining techniques

The search techniques described on this page are not mutually exclusive — combining them often produces the best results.

### Full-text retrieval + reranking

Use full-text search to quickly narrow a large dataset down to a candidate set, then apply reranking to sort those candidates by semantic relevance. This gives you the speed of database-native full-text search with the accuracy of AI-powered relevance scoring:

```php theme={null}
$articles = Article::query()
    ->whereFullText('body', $request->input('query'))
    ->limit(50)
    ->get()
    ->rerank('body', $request->input('query'), limit: 10);
```

### Vector search + traditional filters

Combine vector similarity with standard `where` clauses to scope semantic search to a subset of records. This is useful when you need meaning-based search but want to restrict results by ownership, category, or any other attribute:

```php theme={null}
$documents = Document::query()
    ->where('team_id', $user->team_id)
    ->whereVectorSimilarTo('embedding', $request->input('query'))
    ->limit(10)
    ->get();
```

***

## Related pages

<Card title="Laravel Scout" icon="magnifying-glass" href="/en/scout">
  Complete guide to automatic index syncing with the Searchable trait.
</Card>

<Card title="Laravel AI SDK" icon="sparkles" href="/en/ai-sdk">
  Configure vector embeddings and reranking with the AI SDK.
</Card>

<Card title="Query Builder" icon="database" href="/en/query-builder">
  Detailed reference for whereFullText, whereVectorSimilarTo, and more.
</Card>

<Card title="Migrations" icon="table" href="/en/migrations">
  How to create full-text indexes and vector columns.
</Card>
