PHP code example of devilsberg / laravel-mariadb-vector
1. Go to this page and download the library: Download devilsberg/laravel-mariadb-vector library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
devilsberg / laravel-mariadb-vector example snippets
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->vector('embedding', 768);
$table->vectorIndex('embedding'); // enables fast ANN search
$table->timestamps();
});
use Devilsberg\LaravelMariadbVector\Casts\VectorCast;
class Article extends Model
{
protected function casts(): array
{
return [
'embedding' => VectorCast::class,
];
}
}
$embedding = $yourEmbeddingProvider->embed($article->body); // your code
$article->embedding = $embedding; // float array, e.g. [0.1, 0.2, ...]
$article->save();
use Devilsberg\LaravelMariadbVector\Distance;
$queryVector = $yourEmbeddingProvider->embed('climate change effects');
$results = Article::query()
->nearestNeighbors('embedding', $queryVector, Distance::Cosine)
->limit(10)
->get();
// Each result has a `score` column — higher is more similar (0–1)
foreach ($results as $article) {
echo $article->title . ' — ' . $article->score;
}
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->vector('embedding', 768);
$table->vectorIndex('embedding'); // ALTER TABLE ... ADD VECTOR INDEX runs after CREATE TABLE
$table->timestamps();
});