What native vector query support does Laravel 13 introduce?

Laravel 13 introduces native vector query support that allows you to perform semantic similarity searches directly through Eloquent and the query builder, without needing external vector databases or third-party packages for the core functionality.

Supported Databases

The native support works with two database systems:

PostgreSQL (requires the pgvector extension).
MariaDB (version 11.7 or later) . Support for MariaDB was added natively starting from Laravel 13.

Key Query Methods

You can use fluent query builder methods to interact with vector columns:

→whereVectorSimilarTo( embedding , your search string ): This is the primary method for semantic search. If you have the Laravel AI SDK configured, Laravel automatically converts the search string into an embedding for you.
→orderByVectorDistance(): Orders results by their vector distance (similarity).
→selectVectorDistance() and whereVectorDistanceLessThan(): Additional methods for more granular control over distance calculations.

Example Usage

Here is a simplified example of how you would set up and query a model with a vector column:

1. Migration Create a vector column (dimensions must match your embedding model, e.g., 1536 for many OpenAI models) :

$table->vector( embedding , dimensions: 1536)->index();

2. Model Cast Use the AsVector cast to let Laravel handle the conversion between PHP arrays and the database is vector format:

use IlluminateDatabaseEloquentCastsAsVector;

protected function casts(): array
{
   return [
        embedding => AsVector::class,
   ];
}

3. Query Perform a semantic search directly in your Eloquent query :

$documents = Document::query()
   ->whereVectorSimilarTo( embedding , best wineries in Napa Valley )
   ->limit(10)
   ->get();

Important Note

For MariaDB users, it is crucial to use the dedicated mariadb database driver (not the mysql driver), as vector queries and indexes will throw exceptions otherwise.

12 Views