PHP code example of brynj-digital / laravel-scout-vectorize

1. Go to this page and download the library: Download brynj-digital/laravel-scout-vectorize 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/ */

    

brynj-digital / laravel-scout-vectorize example snippets


public function toSearchableArray(): array
{
    return [
        // These fields are used for both embeddings AND metadata
        'name' => $this->name,
        'description' => $this->description,

        // These fields are stored as metadata for filtering
        // (

Product::search('laptop')
    ->where('status', 'active')
    ->where('in_stock', true)
    ->get();

'driver' => env('SCOUT_DRIVER', 'vectorize'),

use Laravel\Scout\Searchable;

class Product extends Model
{
    use Searchable;

    /**
     * Get the indexable data array for the model.
     */
    public function toSearchableArray(): array
    {
        return [
            'name' => $this->name,
            'description' => $this->description,
            'brand' => $this->brand,
            'category' => $this->category,
        ];
    }
}

class Product extends Model
{
    use Searchable;

    /**
     * Convert the model to searchable text.
     * This method takes precedence over toSearchableArray().
     */
    public function toSearchableText(): string
    {
        return implode('. ', [
            $this->name,
            $this->brand,
            $this->description,
            implode(' ', $this->tags ?? []),
        ]);
    }

    public function toSearchableArray(): array
    {
        return [
            'name' => $this->name,
            'description' => $this->description,
        ];
    }
}

// Simple search
$products = Product::search('wireless headphones')->get();

// Limit results
$products = Product::search('laptop')->take(20)->get();

// Paginate results
$products = Product::search('smartphone')->paginate(15);

// Get raw search results with scores
$results = Product::search('tablet')->raw();

// Index a single model
$product = Product::find(1);
$product->searchable();

// Index all models
Product::makeAllSearchable();

// Using artisan command
php artisan scout:import "App\Models\Product"

// Remove a single model
$product->unsearchable();

// Remove all models of a type
Product::removeAllFromSearch();

// Using artisan command
php artisan scout:flush "App\Models\Product"

// Automatically indexed
$product = Product::create([
    'name' => 'Wireless Headphones',
    'description' => 'High-quality Bluetooth headphones',
]);

// Automatically re-indexed
$product->update(['name' => 'Premium Wireless Headphones']);

// Automatically removed from index
$product->delete();

use Laravel\Scout\Searchable;

class Product extends Model
{
    use Searchable;

    public function toSearchableArray(): array
    {
        return [
            'name' => $this->name,
            'brand' => $this->brand,
            'description' => $this->description,
            'category' => $this->category->name,
            'features' => implode(', ', $this->features ?? []),
            // Metadata for filtering
            'status' => $this->status,
            'price' => $this->price,
            'in_stock' => $this->in_stock,
        ];
    }
}

// Search with semantic understanding
$results = Product::search('laptop for programming and gaming')
    ->where('in_stock', true)
    ->where('status', 'published')
    ->take(20)
    ->get();

class Article extends Model
{
    use Searchable;

    public function toSearchableArray(): array
    {
        return [
            'title' => $this->title,
            'excerpt' => $this->excerpt,
            'content' => strip_tags($this->content),
            'author' => $this->author->name,
            'tags' => $this->tags->pluck('name')->join(', '),
            // Metadata
            'category_id' => $this->category_id,
            'published_at' => $this->published_at,
            'status' => $this->status,
        ];
    }

    public function toSearchableText(): string
    {
        // Custom text format for better embeddings
        return sprintf(
            '%s. %s. Written by %s. Tags: %s',
            $this->title,
            $this->excerpt,
            $this->author->name,
            $this->tags->pluck('name')->join(', ')
        );
    }
}

// Find related articles
$related = Article::search('introduction to machine learning')
    ->where('status', 'published')
    ->where('category_id', $article->category_id)
    ->take(5)
    ->get();

class Documentation extends Model
{
    use Searchable;

    public function toSearchableArray(): array
    {
        return [
            'title' => $this->title,
            'content' => strip_tags($this->content),
            'section' => $this->section,
            'version' => $this->version,
        ];
    }
}

// Semantic search in docs
$docs = Documentation::search('how to handle file uploads')
    ->where('version', config('app.docs_version'))
    ->get();

class SupportTicket extends Model
{
    use Searchable;

    public function toSearchableArray(): array
    {
        return [
            'subject' => $this->subject,
            'description' => $this->description,
            'customer_name' => $this->customer->name,
            'category' => $this->category,
            // Metadata
            'status' => $this->status,
            'priority' => $this->priority,
        ];
    }
}

// Find similar support tickets
$similar = SupportTicket::search($newTicket->description)
    ->where('status', 'resolved')
    ->take(10)
    ->get();

$results = Product::search('laptop', function ($client, $query, $options) {
    // $client is the VectorizeClient instance
    return $client->search($query, 50, [
        'model' => Product::class,
        'in_stock' => true,
    ]);
})->get();

// Search with filters
$products = Product::search('gaming laptop')
    ->where('status', 'published')
    ->where('price', '< 2000')
    ->get();

// Multiple filters
$articles = Article::search('machine learning')
    ->where('category', 'technology')
    ->where('published_at', '>', now()->subDays(30))
    ->get();

use ScoutVectorize\VectorizeClient;

$client = app(VectorizeClient::class);

// Get index information
$info = $client->getIndexInfo();

// Manual search with filters
$results = $client->search(
    query: 'wireless headphones',
    topK: 10,
    filter: ['status' => 'active']
);

// Generate embedding for text
$embedding = $client->generateEmbedding('sample text');

// Batch upsert documents
$client->batchUpsert([
    [
        'id' => 'doc_1',
        'text' => 'Document content',
        'metadata' => ['category' => 'tech'],
    ],
    // ... more documents
]);

// Delete vectors by IDs
$client->deleteVectors(['doc_1', 'doc_2']);

// In config/scout.php
'queue' => true,

// Specify queue connection and queue name
'queue' => [
    'connection' => env('SCOUT_QUEUE_CONNECTION', 'redis'),
    'queue' => env('SCOUT_QUEUE_NAME', 'default'),
],

// config/scout-vectorize.php

return [
    'cloudflare' => [
        'account_id' => env('CLOUDFLARE_ACCOUNT_ID'),
        'api_token' => env('CLOUDFLARE_API_TOKEN'),
    ],

    'index' => env('CLOUDFLARE_VECTORIZE_INDEX', 'default'),

    'embedding_model' => env('CLOUDFLARE_EMBEDDING_MODEL', '@cf/baai/bge-base-en-v1.5'),
];

   public function toSearchableText(): string
   {
       // Good: Includes context
       return "Product: {$this->name}. Brand: {$this->brand}. {$this->description}";

       // Not ideal: Just raw values
       return "{$this->name} {$this->brand} {$this->description}";
   }
   

   public function toSearchableArray(): array
   {
       return [
           'title' => $this->title,
           'excerpt' => Str::limit($this->content, 500), // Limit long content
           'category' => $this->category->name,
       ];
   }
   

   public function toSearchableArray(): array
   {
       return [
           'content' => $this->content,
           // Always 
       ];
   }
   

   // config/scout.php
   'queue' => env('SCOUT_QUEUE', true),
   

   // Good: Limited results
   Product::search('laptop')->take(20)->get();

   // Avoid: Fetching everything
   Product::search('laptop')->get();
   

   $results = Cache::remember(
       "search:{$query}",
       now()->addMinutes(10),
       fn() => Product::search($query)->take(20)->get()
   );
   

   $query = request()->validate(['q' => 'et();
   

   $results = Article::search('security')
       ->where('visibility', 'public')
       ->orWhere('author_id', auth()->id())
       ->get();
   
bash
php artisan vendor:publish --tag=scout-vectorize-config

src/
├── Engines/
│   └── VectorizeEngine.php    # Scout engine implementation
├── VectorizeClient.php         # Cloudflare API client
└── VectorizeServiceProvider.php # Service provider

tests/
├── TestCase.php                # Base test case
└── VectorizeEngineTest.php     # Engine tests