PHPackages                             illuma-law/laravel-vector-schema - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. illuma-law/laravel-vector-schema

ActiveLibrary[Database &amp; ORM](/categories/database)

illuma-law/laravel-vector-schema
================================

Portable Eloquent casts and Blueprint schema macros for pgvector and sqlite-vec.

v1.0.9(1mo ago)060[2 PRs](https://github.com/illuma-law/laravel-vector-schema/pulls)MITPHPPHP ^8.3CI passing

Since Apr 20Pushed 1mo agoCompare

[ Source](https://github.com/illuma-law/laravel-vector-schema)[ Packagist](https://packagist.org/packages/illuma-law/laravel-vector-schema)[ Docs](https://github.com/illuma-law/laravel-vector-schema)[ GitHub Sponsors](https://github.com/illuma-law)[ RSS](/packages/illuma-law-laravel-vector-schema/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (15)Versions (13)Used By (0)

Laravel Vector Schema
=====================

[](#laravel-vector-schema)

[![Tests](https://github.com/illuma-law/laravel-vector-schema/actions/workflows/run-tests.yml/badge.svg)](https://github.com/illuma-law/laravel-vector-schema/actions)[![Packagist License](https://camo.githubusercontent.com/e60623f508586f049d48cfb8396ee411b0c9bc3be174381a1893c37462a3c1e5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e63652d4d49542d626c7565)](http://choosealicense.com/licenses/mit/)[![Latest Stable Version](https://camo.githubusercontent.com/22f23e8e34d51b2935095da126372be2d6204a28499bc2a09dab226f4fc6c426/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f696c6c756d612d6c61772f6c61726176656c2d766563746f722d736368656d613f6c6162656c3d56657273696f6e)](https://packagist.org/packages/illuma-law/laravel-vector-schema)

Portable vector columns and search macros for Laravel Eloquent.

When building AI applications with RAG (Retrieval-Augmented Generation), you must store and query high-dimensional vector embeddings. However, PostgreSQL (`pgvector`), SQLite (`sqlite-vec`), SingleStore, and MySQL all use different syntax for vector data types, index creation, and cosine distance calculations.

This package provides Laravel Blueprint schema macros and Eloquent Builder macros to seamlessly abstract away these database differences, giving you a unified API for vector search across all supported databases.

Features
--------

[](#features)

- **Database Portability:** Write your migrations and vector queries once; the package compiles them to the correct syntax for your active database connection.
- **SQLite Binary Support:** Safely handles the complex float32 `BLOB` packing required by `sqlite-vec` while using native `vector` column types on Postgres/MySQL.
- **HNSW Index Support:** Provides a macro for creating high-performance Approximate Nearest Neighbor (ANN) indexes.
- **Cosine Similarity:** Provides fluent query macros to filter, sort, and select based on vector cosine similarity and distance.
- **Eloquent Cast:** Automatically serializes and deserializes PHP arrays to the correct database vector format.

Database Support Matrix
-----------------------

[](#database-support-matrix)

DatabaseSupport LevelRequirementsDistance Function**PostgreSQL**Native`pgvector` extension`` (Cosine)**MySQL (9.0+)**NativeHeatWave or Enterprise Edition`VECTOR_DISTANCE`**MariaDB (11.7+)**NativeNone`VEC_DISTANCE_COSINE`**SQL Server**NativeAzure SQL (Preview)`VECTOR_DISTANCE`**SingleStore**NativeNone`DOT_PRODUCT`**SQLite**Native`sqlite-vec` extension`vec_distance_cosine`*Note: MySQL Community Edition (GPL) currently restricts the `VECTOR_DISTANCE` function to HeatWave/Enterprise users. SQLite requires loading the `sqlite-vec` extension.*

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require illuma-law/laravel-vector-schema
```

The Service Provider will automatically register the `Blueprint` and `Builder` macros.

Usage &amp; Integration
-----------------------

[](#usage--integration)

### Schema Migrations

[](#schema-migrations)

Use the `vectorColumn` macro to define portable vector columns. On PostgreSQL, MySQL, MariaDB, SQL Server, and SingleStore, this creates a native `vector` column. On SQLite, it safely falls back to a `BLOB` column compatible with `sqlite-vec`.

Use `hnswIndex` for high-performance approximate nearest neighbor (ANN) similarity search. This generates a native HNSW index on PostgreSQL and is gracefully ignored on other drivers.

```
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use IllumaLaw\VectorSchema\VectorSchema;

return new class extends Migration {
    public function up(): void
    {
        // Ensures the pgvector extension is created on PostgreSQL databases
        VectorSchema::ensureExtension();

        Schema::create('documents', function (Blueprint $table) {
            $table->id();
            $table->text('content');

            // Define 'embedding' column with 768 dimensions
            $table->vectorColumn('embedding', 768)->nullable();

            $table->timestamps();
        });

        // Creates an HNSW index on pgsql (ignored on others)
        Schema::table('documents', function (Blueprint $table) {
            $table->hnswIndex('embedding');
        });
    }

    public function down(): void
    {
        Schema::table('documents', function (Blueprint $table) {
            $table->dropHnswIndex('embedding');
        });
        Schema::dropIfExists('documents');
    }
};
```

### Eloquent Casts

[](#eloquent-casts)

Add the `VectorArray` cast to your Eloquent model. This handles the serialization and deserialization of plain PHP arrays into the specific formats required by your active database driver.

```
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use IllumaLaw\VectorSchema\Casts\VectorArray;

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

Now you can interact with the vector just like a normal array:

```
$document = new Document();
$document->content = 'Hello world';
$document->embedding = [0.1, 0.5, -0.3, ...]; // Will be cast correctly on save
$document->save();
```

### Vector Math Utilities (`VectorProcessor`)

[](#vector-math-utilities-vectorprocessor)

When dealing with high-dimensional vectors, you often need to perform common mathematical operations such as normalizing input data or averaging several vectors (e.g., to create a centroid for a cluster or a search query).

The package includes a domain-agnostic `VectorProcessor` class for these tasks.

#### `normalizeVector`

[](#normalizevector)

Ensures an input vector is a flat list of floats, filters out `NaN` or `INF` values, and validates the expected dimensionality. Returns an empty array if the input is invalid.

```
use IllumaLaw\VectorSchema\Support\VectorProcessor;

$processor = new VectorProcessor();

// Returns a list of length 3
$normalized = $processor->normalizeVector([0.5, '1.5', 2], expectedDimensions: 3);

if ($normalized === []) {
    // Handle invalid input or dimension mismatch
}
```

#### `averageVectors`

[](#averagevectors)

Computes the mathematical average (centroid) of a collection of vectors. This is useful for combining multiple embeddings into a single query vector.

```
$processor = new VectorProcessor();

$vectors = [
    [1.0, 1.0, 1.0],
    [3.0, 3.0, 3.0],
    [NAN, 0.0, 0.0], // Automatically filtered out
];

// Returns [2.0, 2.0, 2.0]
$centroid = $processor->averageVectors($vectors, expectedDimensions: 3);
```

### Vector Querying (Semantic Search)

[](#vector-querying-semantic-search)

The package provides several macros attached to the Laravel Query Builder.

#### `whereHybridVectorSimilarTo`

[](#wherehybridvectorsimilarto)

Filter results to only include those that meet a minimum cosine similarity threshold. You can also ask the macro to automatically order the results by similarity (closest first).

```
// Assuming $queryEmbedding is an array of 768 floats from your Embedding model (e.g., OpenAI)
$queryEmbedding = [...];

$results = Document::query()
    ->whereHybridVectorSimilarTo(
        column: 'embedding',
        vector: $queryEmbedding,
        minSimilarity: 0.7,
        order: true // Automatically order by the closest match
    )
    ->take(10)
    ->get();
```

#### `selectHybridVectorDistance`

[](#selecthybridvectordistance)

Select the raw cosine distance between a stored vector and your query vector into a dynamically named alias. Note that distance is the inverse of similarity (0.0 is an exact match).

```
$results = Document::query()
    ->select('id', 'content')
    ->selectHybridVectorDistance('embedding', $queryEmbedding, as: 'distance')
    ->orderBy('distance', 'asc') // Closest first
    ->get();

echo $results->first()->distance;
```

#### `whereHybridVectorDistanceLessThan`

[](#wherehybridvectordistancelessthan)

If you prefer thinking in distances rather than similarities, directly filter by the raw distance.

```
$results = Document::query()
    ->whereHybridVectorDistanceLessThan('embedding', $queryEmbedding, maxDistance: 0.3)
    ->get();
```

#### `orderByHybridVectorDistance`

[](#orderbyhybridvectordistance)

If you only need to order results by semantic proximity without filtering or selecting the specific distance value:

```
$results = Document::query()
    ->orderByHybridVectorDistance('embedding', $queryEmbedding, 'asc')
    ->get();
```

Testing
-------

[](#testing)

The package includes a comprehensive test suite using Pest.

```
composer test
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance91

Actively maintained with recent releases

Popularity12

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 90.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~1 days

Total

10

Last Release

43d ago

Major Versions

v0.1.0 → v1.0.62026-04-20

### Community

Maintainers

![](https://www.gravatar.com/avatar/2affac64f2726a640084b203503518ca01f582536d60a0a299b614486ed95aaa?d=identicon)[miguelenes](/maintainers/miguelenes)

---

Top Contributors

[![miguelenes](https://avatars.githubusercontent.com/u/1568086?v=4)](https://github.com/miguelenes "miguelenes (28 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (1 commits)")

---

Tags

laravelilluma-lawlaravel-vector-schema

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/illuma-law-laravel-vector-schema/health.svg)

```
[![Health](https://phpackages.com/badges/illuma-law-laravel-vector-schema/health.svg)](https://phpackages.com/packages/illuma-law-laravel-vector-schema)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3325.1M337](/packages/psalm-plugin-laravel)[spatie/laravel-health

Monitor the health of a Laravel application

88011.3M149](/packages/spatie-laravel-health)[clickbar/laravel-magellan

This package provides functionality for working with the postgis extension in Laravel.

436834.4k1](/packages/clickbar-laravel-magellan)[laravel/ai

The official AI SDK for Laravel.

9782.1M153](/packages/laravel-ai)[watson/validating

Eloquent model validating trait.

9743.4M53](/packages/watson-validating)[simplestats-io/laravel-client

Analytics for Laravel. Track visitors, registrations, and payments. Discover which channels actually drive revenue, not just traffic. Server-side, GDPR compliant, ad-blocker proof.

5019.3k](/packages/simplestats-io-laravel-client)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
