What is the new AsVector Eloquent cast used for in Laraval 13?

The AsVector Eloquent cast in Laravel 13 is used to seamlessly handle vector column data in your models, allowing you to read and write embeddings as native PHP arrays instead of dealing with raw binary or JSON formats.

Primary Purpose

It acts as a bridge between your database is vector storage format and your application code. Without it, you would have to manually encode/decode the data, which is especially tricky with MariaDB is binary format.

Key Capabilities

  • Reads as Arrays: When you access the attribute, it automatically converts the database is vector representation (MariaDB binary or PostgreSQL text) into a standard PHP array of floats.
  • Writes from Arrays: When you save a model, you can assign a plain PHP array (or any Arrayable object like a Collection) to the vector column, and the cast handles the conversion for the database.
  • Driver Portability: It works across different database drivers. For MariaDB, it handles the binary decoding and uses server-side conversion (vec_fromtext) when writing. For PostgreSQL (pgvector), it stores the data as JSON text, which pgvector accepts.

Example Usage

You simply define it in your model is $casts property:

use IlluminateDatabaseEloquentCastsAsVector;

class Document extends Model
{
   protected $casts = [
        embedding => AsVector::class,
   ];
}

Once set up, you can interact with the embedding column naturally:

// Writing an array
$document->embedding = [0.1, 0.2, 0.3];

// Reading it back gives you an array
$vector = $document->embedding;  

This cast is a crucial piece that makes Laravel is native vector search features (like whereVectorSimilarTo) practical to use within your Eloquent models.

3 Views