How does the AsVector cast Handle MariaDB Binary Vectors in Laravel 13 With Example?

In Laravel 13, the AsVector cast handles MariaDB is binary vectors through a two-way conversion mechanism: when reading, it decodes the binary bytes into a PHP floating-point array; when writing, it converts the array into a vec_fromtext( [...] ) expression and lets MariaDB perform the conversion on the server side.

How It Works?

Reading (Database → PHP) MariaDB is VECTOR column stores data in little-endian float32 binary format. When you access the model is vector property, AsVector decodes the raw bytes returned by MariaDB into a PHP array using unpack( g* ).

Writing (PHP → Database) When you assign an array (or an Arrayable object such as a Collection) to a vector property, AsVectordoes not bind the raw binary or a JSON string directly. Instead, it generates a vec_fromtext( [...] ) expression, allowing MariaDB is server-side function to convert the text into an internal vector format . This avoids SQL errors that can occur when binding raw data directly.

Complete Example

1. Migration: Create the Vector Column

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


On MariaDB, do not call Schema::ensureVectorExtensionExists(); that is a pgvector helper and will throw an error on MariaDB .

2. Model: Enable the Cast

use IlluminateDatabaseEloquentCastsAsVector;

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


3. Writing Data

Document::create([
  notitle     => Napa Valley Wine Guide ,
  embedding => $embedding, // Plain PHP float array
]);


The cast automatically handles the conversion to the vec_fromtextexpression .

4. Reading Data

$document = Document::find(1);
$vector = $document->embedding; // Standard PHP float array


5. Semantic Search

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


Thanks to the cast is proper handling of the write direction, vector distance queries can execute normally.

10 Views