Polyscope - The agent-first dev environment for Laravel

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
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi
Lucky Media logo

Lucky Media

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

Lucky Media
Shift logo

Shift

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

Shift
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
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
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
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
PhpStorm logo

PhpStorm

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

PhpStorm
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
SerpApi logo

SerpApi

Access real-time search engine results through a simple API—no more scraping headaches! Use it for AI applications, SEO tools, product research, travel information, and more

SerpApi

The latest

View all →
Moat: A Security Review for Your GitHub Account image

Moat: A Security Review for Your GitHub Account

Read article
Laravel Paper: A Flat-File Eloquent Driver image

Laravel Paper: A Flat-File Eloquent Driver

Read article
Simple Feature Flags for Laravel with Laravel Toggle image

Simple Feature Flags for Laravel with Laravel Toggle

Read article
Manage Laravel Cloud Deployments Inside PhpStorm image

Manage Laravel Cloud Deployments Inside PhpStorm

Read article
Piper: Laravel-Style Array and String Helpers for PHP's Pipe Operator image

Piper: Laravel-Style Array and String Helpers for PHP's Pipe Operator

Read article
Storage Cache Store in Laravel 13.10.0 image

Storage Cache Store in Laravel 13.10.0

Read article