PHP code example of vlados / laravel-related-content
1. Go to this page and download the library: Download vlados/laravel-related-content 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/ */
vlados / laravel-related-content example snippets
use Vlados\LaravelRelatedContent\Concerns\HasRelatedContent;
class BlogPost extends Model
{
use HasRelatedContent;
/**
* Define which fields should be embedded.
*/
public function embeddableFields(): array
{
return ['title', 'excerpt', 'content'];
}
}
$post = BlogPost::create([
'title' => 'Electric Vehicle Charging Guide',
'content' => '...',
]);
// Embedding is generated and related content is found automatically
// Get all related content
$related = $post->getRelatedModels();
// Get related content of a specific type
$relatedEvents = $post->getRelatedOfType(Event::class);
// Get the raw relationship with similarity scores (this model as source only)
$post->relatedContent()->with('related')->get();
use Vlados\LaravelRelatedContent\Services\RelatedContentService;
$service = app(RelatedContentService::class);
// Search across all embeddable models
$results = $service->search('electric vehicle charging');
// Search specific model types
$results = $service->search('charging stations', [
\App\Models\Event::class,
\App\Models\BlogPost::class,
]);
// By default search returns the closest N matches regardless of distance.
// Pass a minimum similarity (0-1) to filter out weak matches:
$results = $service->search('charging stations', [], limit: 10, threshold: 0.5);
use Vlados\LaravelRelatedContent\Events\RelatedContentSynced;
class HandleRelatedContentSynced
{
public function handle(RelatedContentSynced $event): void
{
// $event->model - The model that was synced
}
}