# How to Run Laravel 13 MariaDB Vector Search on xCloud

> Set up MariaDB vector search in Laravel 13: vector column and index, AsVector cast, whereVectorSimilarTo, queued embeddings, and running it on xCloud.

**MariaDB vector search** works in Laravel 13 without a second database. Since Laravel 13.28, a `vector()` column, a vector index, the `AsVector` cast and `whereVectorSimilarTo()` run natively on MariaDB 11.7 or later over the `mariadb` driver. On xCloud, you get MariaDB 11.8 LTS by choosing MariaDB when you create the server.

Until this autumn, semantic search in Laravel meant PostgreSQL with pgvector, or a separate vector service next to your MySQL-family database. The [MariaDB Foundation announced](https://mariadb.org/laravel-13-now-supports-mariadb-vector-natively/) on 7 October 2026 that this gap is closed: your posts, products and help articles can keep their embeddings in the same MariaDB database as everything else.

This guide shows the whole path for a [**Laravel app**](/laravel-hosting/): the migration, storing embeddings with the Laravel AI SDK, the similarity query, a queued embedding job, and then running it on an xCloud server with the right `.env`, a queue worker and the scheduler.

## TL;DR

Short on time? Here is the whole guide in a few lines:

- **You need three things:** Laravel 13.28 or newer, MariaDB 11.7 or newer (11.8 is the LTS) and `DB_CONNECTION=mariadb`. The `mysql` driver throws on vector queries.
- **Schema:** `$table->vector('embedding', dimensions: 1536)->index()` creates a `VECTOR` column and a cosine vector index.
- **Model:** cast the column with `AsVector::class`, so you read and write plain PHP arrays of floats.
- **Query:** `whereVectorSimilarTo('embedding', 'your search text')` embeds the text through the Laravel AI SDK and orders results by similarity.
- **MariaDB rules that bite:** one vector index per table, the indexed column must be `NOT NULL`, and the index is used only for `ORDER BY` distance with a `LIMIT`.
- **On xCloud:** pick MariaDB 11.8 at server creation, deploy from Git, and xCloud writes `DB_CONNECTION=mariadb` for a Laravel 11+ app on that server. Generate embeddings in a queue worker.

## The One Setting That Breaks Most First Attempts

Here's the part that trips people up: **MariaDB speaks the MySQL protocol, so a Laravel app on MariaDB often runs with `DB_CONNECTION=mysql` for years without a problem.** Vector search is where that stops. Laravel checks the connection before it builds a vector query, and only PostgreSQL and MariaDB connections pass; the rest get "Vector distance queries are only supported by Postgres and MariaDB." The MariaDB Foundation's own write-up says the `mysql` driver "appears to work" until a vector query or vector index throws.

On xCloud this is handled when the site is created. The code that writes a Laravel site's `.env` sets `DB_CONNECTION=mariadb` only when both of these are true:

1. the server's database is **MariaDB**, and
2. the app has a `mariadb` connection: its `config/database.php` defines a `'mariadb'` key (every Laravel 11, 12 and 13 app does), or its `.env` / `.env.example` already says `DB_CONNECTION=mariadb`.

Everything else gets `mysql`, because Laravel 10 and older have no `mariadb` connection and would fail with "Database connection [mariadb] not configured". So a fresh Laravel 13 app deployed to a MariaDB 11.8 server on xCloud starts on the right driver. A site you created before, or one on a MySQL server, needs a check (covered in the setup steps below).

## What You Need Before You Start

| Requirement | Minimum | Why it matters |
|---|---|---|
| **Laravel** | 13.28 | The first release with working MariaDB vector distance SQL and the `AsVector` cast |
| **PHP** | 8.3 | Laravel 13's own requirement (`"php": "^8.3"`); xCloud offers 8.3, 8.4 and 8.5 |
| **MariaDB** | 11.7, use 11.8 LTS | `VECTOR` arrived in 11.7; 11.8 is the first long-term support release with it |
| **Driver** | `DB_CONNECTION=mariadb` | Vector queries and indexes throw on the `mysql` driver |
| **Laravel AI SDK** | `laravel/ai` | Generates embeddings and turns search text into a vector |
| **Embedding provider key** | e.g. `OPENAI_API_KEY` | The SDK calls your provider; that bill is separate from hosting |

If you're new to the framework, our [**beginner's guide to Laravel**](/what-is-laravel-a-complete-beginners-guide/) covers the basics this post assumes.

## How Laravel 13 Talks to MariaDB Vectors

Laravel gives you four query methods and they compile to MariaDB's cosine functions. This is the map worth keeping open while you code:

| Laravel method | What it does | MariaDB under the hood |
|---|---|---|
| `whereVectorSimilarTo($column, $vector, minSimilarity: 0.6, order: true)` | Filters by cosine similarity (0.0 to 1.0) and orders by it | `VEC_DISTANCE_COSINE(column, VEC_FromText(?))` |
| `whereVectorDistanceLessThan($column, $vector, maxDistance: 0.3)` | Keeps rows closer than a distance | Same function, as a `WHERE` |
| `orderByVectorDistance($column, $vector)` | Sorts nearest first | Same function, in `ORDER BY` |
| `selectVectorDistance($column, $vector, as: 'distance')` | Returns the distance as a column | Same function, in `SELECT` |
| `$table->vector(...)->index()` / `vectorIndex()` | Adds a vector index | `VECTOR INDEX` with cosine distance |
| `dropVectorIndex('documents_embedding_vectorindex')` | Removes it | `DROP INDEX` |

Two defaults are worth knowing. `whereVectorSimilarTo` uses `minSimilarity: 0.6` when you pass nothing, and when you pass a plain string instead of an array it embeds the string with the AI SDK and caches that embedding. The full reference is in the [**Laravel query builder docs**](https://laravel.com/docs/13.x/queries#vector-similarity-clauses).

## Step 1: Install the Laravel AI SDK

The AI SDK is the part that turns text into vectors. Install it, publish its config and run its migrations:

```bash
composer require laravel/ai
php artisan vendor:publish --provider="Laravel\Ai\AiServiceProvider"
php artisan migrate
```

Then add your provider's key to `.env`. The SDK supports several embedding providers, including OpenAI, Gemini, Cohere, Mistral, Jina, VoyageAI and Ollama:

```bash
DB_CONNECTION=mariadb
OPENAI_API_KEY=your-key-here
```

The default embedding model and dimensions live in `config/ai.php`.

## Step 2: Create the Vector Table and Index

MariaDB has two rules that shape this migration. **The indexed vector column must be `NOT NULL`, and a table can have only one vector index.** If you add a nullable `embedding` column to your `documents` table and fill it later from a queue, you can't index it.

The clean answer is a separate table that holds one row per embedded document. A row only exists once its embedding exists, so the column stays `NOT NULL`:

```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('document_embeddings', function (Blueprint $table) {
            $table->id();
            $table->foreignId('document_id')->unique()->constrained()->cascadeOnDelete();
            $table->vector('embedding', dimensions: 1536)->index();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('document_embeddings');
    }
};
```

Don't call `Schema::ensureVectorExtensionExists()` here. That helper loads pgvector on PostgreSQL and throws on MariaDB, where `VECTOR` is a built-in type.

**Match `dimensions` to your embedding model.** The Laravel docs use 1536 with OpenAI's `text-embedding-3-small`. A model that returns a different length needs a different number, and changing it later means re-embedding every row.

## Step 3: Cast the Column on the Model

The `AsVector` cast hides MariaDB's storage format. On read it unpacks the binary float32 bytes MariaDB returns; on write it wraps your array in `VEC_FromText()`:

```php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\AsVector;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class DocumentEmbedding extends Model
{
    protected $fillable = ['document_id', 'embedding'];

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

    public function document(): BelongsTo
    {
        return $this->belongsTo(Document::class);
    }
}
```

## Step 4: Generate Embeddings in a Queued Job

An embedding call goes out to your provider over the network, so don't make a visitor wait for it. Put it in a job:

```php
<?php

namespace App\Jobs;

use App\Models\Document;
use App\Models\DocumentEmbedding;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Str;

class EmbedDocument implements ShouldQueue
{
    use Queueable;

    public function __construct(public Document $document) {}

    public function handle(): void
    {
        $vector = Str::of($this->document->title."\n\n".$this->document->content)
            ->toEmbeddings();

        DocumentEmbedding::updateOrCreate(
            ['document_id' => $this->document->id],
            ['embedding' => $vector],
        );
    }
}
```

Dispatch it whenever a document is saved, for example from the model's `saved` event:

```php
protected static function booted(): void
{
    static::saved(fn (Document $document) => EmbedDocument::dispatch($document));
}
```

For a backfill of many rows, the SDK can embed several inputs in one request with `Embeddings::for([...])->generate()`, which saves round trips.

## Step 5: Run the Similarity Search

Now the payoff. Pass the visitor's words straight in; Laravel embeds them and returns the closest documents first:

```php
use App\Models\DocumentEmbedding;

$results = DocumentEmbedding::query()
    ->with('document')
    ->whereVectorSimilarTo('embedding', $request->string('q'), minSimilarity: 0.4)
    ->limit(10)
    ->get()
    ->pluck('document');
```

If you need the score for display or debugging, use the lower-level methods together:

```php
$results = DocumentEmbedding::query()
    ->select('*')
    ->selectVectorDistance('embedding', $queryEmbedding, as: 'distance')
    ->orderByVectorDistance('embedding', $queryEmbedding)
    ->limit(10)
    ->get();
```

**Always keep a `limit()`.** MariaDB's [vector documentation](https://mariadb.com/docs/server/reference/sql-structure/vectors/vector-overview) is clear that the optimizer uses the vector index only for an ascending `ORDER BY` on the distance with a `LIMIT`. A distance threshold on its own, without that ordering, reads every row.

If you're building an agent rather than a search box, the AI SDK's `SimilaritySearch::usingModel(DocumentEmbedding::class, 'embedding')` tool lets the agent run this same query itself.

## Run It on xCloud: MariaDB 11.8, Git Deploy and a Queue Worker

This is where the hosting choice matters. Your app now needs MariaDB 11.7+, PHP 8.3+, a long-running queue worker and a scheduler. Here is how that looks on an **xCloud Managed** server.

### 1. Create a server with MariaDB 11.8

Go to **Servers → New Server**, choose **xCloud Managed** hosting and fill in the form. In **'Select Database Server'**, choose **MariaDB**; the version list shows **11.8**, the only MariaDB version xCloud installs on new servers. The install stops with an error instead of finishing on an older, unpatched MariaDB.

**Pick this carefully: the database is fixed when the server is created.** You can't switch a MySQL server to MariaDB later. If your Laravel app already runs on an xCloud MySQL 8.4 server, create a MariaDB server and [**clone the site to it**](/docs/clone-site-under-same-different-server-in-xcloud/). 👉 [Install MariaDB with xCloud](/docs/install-mariadb-with-xcloud/)

### 2. Deploy the Laravel app from Git

Open **Sites → Add New Site → Deploy via Git**, pick the server and paste your repository URL. xCloud detects Laravel, matches **'PHP Version'** to your `composer.json` and, under **'Database Management'**, **'Create Database In Server'** creates the database on your MariaDB server.

![The Deploy via Git form in xCloud showing PHP Version 8.3 matched from composer.json and Create Database In Server under Database Management](/_landing/docs/deploy-laravel-applications-image-8.png)

The default deploy script runs `composer install`, `artisan migrate --force` and `config:cache` after every deploy, so your `document_embeddings` migration runs on the first deploy. 👉 [Deploy Laravel applications on xCloud](/docs/deploy-laravel-applications/)

### 3. Check the .env and add your API key

Open the site and go to **'Laravel' → 'Environment'**. Confirm `DB_CONNECTION=mariadb` and add your embedding provider key, then click **Update Environment**. xCloud refreshes the cached config for you, so no redeploy is needed.

![The Laravel Environment page in xCloud with the site's .env file open in the editor](/_landing/docs/environment-variables-and-git-deployments-in-xcloud-image-2.png)

If the line says `mysql` (an older site, or an app whose `config/database.php` has no `mariadb` key), change it to `mariadb` here. 👉 [Environment variables and Git deployments](/docs/environment-variables-and-git-deployments-in-xcloud/)

### 4. Add a queue worker for the embedding jobs

Go to **'Laravel' → 'Application'**, find the **Laravel Queue** card and click **'Add Queue Worker'**. Set the **Connection** your app uses (`database` or `redis`), the **Queue** name and a **Maximum Seconds Per Job** long enough for a provider call. xCloud keeps the worker running under Supervisor.

![The Add Queue Worker form in xCloud with Connection, Queue, Maximum Seconds Per Job, Maximum Memory and Number of Processes](/_landing/docs/set-up-queue-worker-for-laravel-applications-image-2.png)

Add `$XCLOUD_PHP artisan queue:restart` to your deploy script so workers pick up new code. 👉 [Set up a queue worker for Laravel](/docs/set-up-queue-worker-for-laravel-applications/)

### 5. Schedule re-embedding (optional)

If you re-embed changed content on a timer, add a cron job that runs `php artisan schedule:run` every minute. 👉 [Add a custom cron job in xCloud](/docs/add-a-custom-cron-job-in-xcloud/)

To ship schema changes without a visible gap, turn on [**Release mode for Laravel**](/docs/zero-downtime-deploys-for-laravel-and-php-sites/) so each deploy builds beside the live release and switches in one step.

## Honest Limits: When MariaDB Vector Search Is Not the Right Fit

MariaDB vectors are the simplest option when your data already lives in MariaDB. They're not the answer to everything, and the catch worth knowing is that Laravel's MariaDB support is new.

- **Cosine only in the framework.** Euclidean distance and the index's `M` setting come from a community package, not Laravel itself.
- **One vector index per table, on a `NOT NULL` column.** Several embeddings per row (title and body, or two models) need separate tables.
- **No hybrid search yet.** Full-text plus vector in one query is still being explored for Laravel on MariaDB, per the MariaDB Foundation.
- **Index memory.** The vector index has its own cache, set by MariaDB's `mhnsw_max_cache_size` variable, so large collections need memory planning. The xCloud dashboard tunes general settings such as connections and buffer sizes ([**Configure MySQL and MariaDB with xCloud**](/docs/configure-mysql-and-mariadb-with-xcloud/)); this variable is not one of them.
- **Laravel 12 and older.** No built-in support; you need a package or an upgrade first.

| If you… | A better fit may be |
|---|---|
| Already run PostgreSQL, or need PostGIS and vectors together | PostgreSQL with pgvector. xCloud has a [**pgvector one-click app**](/pgvector-hosting/), and our [**PostgreSQL vs MySQL**](/postgresql-vs-mysql/) comparison covers the wider choice |
| Need hybrid keyword-plus-vector ranking today | A search engine with vectors, alongside your app database |
| Store hundreds of millions of vectors with heavy filtering | A dedicated vector database |
| Have a Laravel app on MariaDB and a few million documents or fewer | **MariaDB vectors, in the database you already back up** |

Treat this as a starting point rather than a strict rule. We haven't benchmarked MariaDB vectors on xCloud, so test with your own data before you commit a large collection.

## Ship Semantic Search on the Database You Already Have

If you only remember one line: **Laravel 13.28+, MariaDB 11.8 and `DB_CONNECTION=mariadb` are all it takes**, and the third one is the setting people miss. Put embeddings in their own `NOT NULL` table, generate them in a queue, and always query with a `limit()`.

This week, create a MariaDB 11.8 server on [**xCloud's Laravel hosting**](/laravel-hosting/), deploy your app from Git and add the five steps above to one model. Compare the results with your current keyword search before you roll it out further. Still choosing where to host? Our [**Laravel hosting comparison**](/best-laravel-hosting-for-developers/) lays out the options, and [**pricing**](/pricing/) shows the plans.

If you have found this blog helpful, feel free to [**subscribe to our blogs**](https://xcloud.host/blog/) for valuable tutorials, guides, knowledge, and tips on web hosting and server management. You can also join our [**Facebook community**](https://www.facebook.com/groups/xcloud.community) to share insights and engage in discussions.

## Frequently Asked Questions

### Which Laravel version supports MariaDB vector search?

Laravel 13.28 and later. That release fixed the MariaDB vector distance SQL and added the AsVector cast. Laravel 12 has no built-in MariaDB vector support; the MariaDB Foundation points Laravel 12 users to the community package devilsberg/laravel-mariadb-vector.

### Do I need DB_CONNECTION=mariadb, or does mysql work?

You need mariadb. Laravel only runs vector queries on PostgreSQL and MariaDB connections, so the mysql driver throws an error even when the server is MariaDB. On xCloud, a new Laravel site on a MariaDB server gets DB_CONNECTION=mariadb written for you when the app has a mariadb connection, which every Laravel 11 or newer app has.

### Can I use MariaDB vector search on a MySQL 8.4 server?

No. Laravel's vector columns and queries work on PostgreSQL with pgvector and on MariaDB 11.7 or later, not on MySQL. On xCloud the database is chosen when the server is created, so create a new server with MariaDB 11.8 and clone your site to it.

### Does Laravel support Euclidean distance on MariaDB?

Not in the framework itself. Laravel's vector methods and vector index use cosine distance. The MariaDB Foundation lists the community package rhaima96/laravel-vector-metrics for Euclidean distance and index tuning; if you change the metric, build the index with the same one.

### Why is my vector query slow even with an index?

MariaDB uses the vector index only for an ascending ORDER BY on the distance with a LIMIT. A distance threshold without ORDER BY and LIMIT reads the whole table. Keep whereVectorSimilarTo's ordering on, always add limit(), and make sure the query uses the same distance as the index.
