Get expert guidance in a few days with a Laravel code review

Laravel Related Content: Semantic Relationships Using pgvector

Published on by

Laravel Related Content: Semantic Relationships Using pgvector image

Finding related content in a Laravel application often means building custom queries or relying on keyword matching, which misses semantic connections. Laravel Related Content, created by Vladislav Stoitsov, uses vector embeddings and PostgreSQL's pgvector extension to automatically discover and link related content across different model types based on meaning rather than keywords. The package is currently in beta at the time of this writing.

The package pre-computes relationships at save time and stores them as database records, so retrieving related content is a standard database query (~5ms) instead of a real-time similarity search on every page load.

Main Features

  • Pre-computed Related Links: Related content is calculated on save, not on every page load
  • Fast Lookups: O(1) relationship queries instead of real-time similarity search
  • Cross-Model Relationships: Find related content across different model types (e.g. an Article can surface related Events or Community Links)
  • Multiple Embedding Providers: Support for OpenAI and Ollama
  • Queue Support: Process embeddings in the background
  • Semantic Search: Search content by meaning, not just keywords

Getting Started

The package requires PostgreSQL with the pgvector extension. If you haven't enabled it yet, run the following in your database:

CREATE EXTENSION IF NOT EXISTS vector;

After installing the package and running its migrations, configure your embedding provider in .env. For OpenAI:

RELATED_CONTENT_PROVIDER=openai
OPENAI_API_KEY=your-api-key
OPENAI_EMBEDDING_MODEL=text-embedding-3-small
OPENAI_EMBEDDING_DIMENSIONS=1536

Or for a local Ollama instance:

RELATED_CONTENT_PROVIDER=ollama
OLLAMA_BASE_URL=http://localhost:11434
OLLAMA_EMBEDDING_MODEL=nomic-embed-text
OLLAMA_EMBEDDING_DIMENSIONS=768

Adding Related Content to Models

Add the HasRelatedContent trait to any model and define which fields should be used for generating embeddings:

class Article extends Model
{
use HasRelatedContent;
 
public function embeddableFields(): array
{
return ['title', 'excerpt', 'content'];
}
}

When a model is saved, the package generates an embedding from the specified fields and finds related content across all configured models.

Retrieving Related Content

Retrieve related models with a single method call:

// Get all related models
$related = $article->getRelatedModels();
 
// Limit the number of results
$related = $article->getRelatedModels(5);
 
// Get related models of a specific type
$events = $article->getRelatedOfType(Event::class);

Since relationships are pre-computed, these calls are standard database queries with no additional API requests.

Cross-Model Relationships

One of the package's notable features is the ability to link content across different models. Register the models that should participate in cross-model relationships in config/related-content.php, and the package will find connections between them automatically. An article about "Laravel testing" could surface a related conference event or community link on the same topic.

'models' => [
\App\Models\Article::class,
\App\Models\Event::class,
\App\Models\CommunityLink::class,
],

Then, semantically search across all configured models by meaning rather than exact keywords:

$service = app(RelatedContentService::class);
$results = $service->search('Laravel AI tools and best practices');

This returns matching content from any registered model type based on the semantic similarity of the query to stored embeddings.

Rebuilding Embeddings

Use the included Artisan command to generate embeddings for existing records or regenerate them after changing embeddable fields:

# Process models that are missing embeddings
php artisan related-content:rebuild
 
# Process a specific model (missing only)
php artisan related-content:rebuild "App\Models\Article"
 
# Regenerate all embeddings
php artisan related-content:rebuild --force
 
# Process synchronously instead of queuing
php artisan related-content:rebuild --sync

Events

The package also dispatches a RelatedContentSynced event when relationships are updated, allowing you to trigger additional logic such as cache invalidation or notifications.

To learn more about Laravel Related Content and view the source code, visit the GitHub repository.

Yannick Lyn Fatt photo

Staff Writer at Laravel News and Full stack web developer.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit

The latest

View all →
Laravel Related Content: Semantic Relationships Using pgvector image

Laravel Related Content: Semantic Relationships Using pgvector

Read article
Filament v5.2.0 Adds a Callout Component image

Filament v5.2.0 Adds a Callout Component

Read article
OpenAI Releases GPT-5.3-Codex, a New Codex Model for Agent-Style Development image

OpenAI Releases GPT-5.3-Codex, a New Codex Model for Agent-Style Development

Read article
Claude Opus 4.6 adds adaptive thinking, 128K output, compaction API, and more image

Claude Opus 4.6 adds adaptive thinking, 128K output, compaction API, and more

Read article
Laravel Announces Official AI SDK for Building AI-Powered Apps image

Laravel Announces Official AI SDK for Building AI-Powered Apps

Read article
`hasMany()` Collection Method in Laravel 12.50.0 image

`hasMany()` Collection Method in Laravel 12.50.0

Read article