Download the PHP package brynj-digital/laravel-scout-vectorize without Composer

On this page you can find all versions of the php package brynj-digital/laravel-scout-vectorize. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-scout-vectorize

Cloudflare Vectorize Driver for Laravel Scout

A Laravel Scout driver for Cloudflare Vectorize, enabling semantic search using vector embeddings in your Laravel applications.

Features

Requirements

Installation

Install the package via Composer:

Publish the configuration file:

Configuration

1. Create a Vectorize Index

Use the provided artisan command to create a Vectorize index:

Alternative: Using Wrangler CLI

The dimensions must match your chosen embedding model:

2. Create Metadata Indexes

Create metadata indexes to enable efficient filtering using the artisan commands:

Note: Recent versions of this package no longer require a key metadata index, as model keys are now extracted directly from the vector ID format. This provides cleaner metadata and reduced storage requirements.

Optional: Additional Metadata Indexes for where() Clauses

You can create additional metadata indexes for any custom fields you want to filter on using Scout's where() method:

Alternative: Using Wrangler CLI

Managing Metadata Indexes

Use the provided commands to manage your metadata indexes:

To use these filters, include the fields in your model's toSearchableArray():

Then use where() in your searches:

How it works: All fields from toSearchableArray() are:

  1. Converted to text and used to generate the embedding vector for semantic search
  2. Stored as metadata for filtering with where() clauses

This means you can search semantically while also applying exact-match filters.

3. Create API Token

You'll need a Cloudflare API token with Vectorize permissions to allow Laravel to interact with your Vectorize index.

Create the token in Cloudflare Dashboard:

  1. Log in to your Cloudflare Dashboard
  2. Navigate to My Profile (click your user icon in the top right)
  3. Select API Tokens from the left sidebar
  4. Click Create Token
  5. Choose Create Custom Token
  6. Configure your token:
    • Token name: Give it a descriptive name (e.g., "Laravel Scout Vectorize")
    • Permissions: Add the following two permissions:
      • Account → VectorizeRead
      • Account → VectorizeWrite
    • Account Resources: Select your specific account (or "All accounts" if needed)
    • TTL: Set an expiration date or leave as default
  7. Click Continue to summary
  8. Review the permissions and click Create Token
  9. Important: Copy the token immediately - it will only be shown once
  10. Store the token securely (you'll add it to your .env file in the next step)

Token Permissions Summary

Your token must have these permissions:

Security Note: Avoid using tokens with broader permissions (like "Account Settings: Read" or "Workers: Edit") unless absolutely necessary.

4. Environment Variables

Add the following to your .env file:

5. Scout Configuration

Ensure Scout is configured in config/scout.php:

Usage

Basic Model Setup

Add the Searchable trait to your model:

Custom Text Conversion (Optional)

For more control over how your model is converted to searchable text, implement a toSearchableText() method:

Searching

Indexing

Removing from Index

Model Observers

Scout automatically syncs your models when you create, update, or delete them:

Practical Examples

E-commerce Product Search

Blog Article Search

Documentation Search

Customer Support Ticket Search

Advanced Usage

Custom Search Callbacks

For advanced search requirements, use a callback:

Using Where Clauses for Filtering

You can combine semantic search with metadata filtering:

Note: Filters are applied to metadata stored in Vectorize. Make sure the fields you filter on are:

  1. Included in your model's toSearchableArray()
  2. Have corresponding metadata indexes created in Vectorize (see Configuration section)

Querying the Client Directly

Queueing Scout Operations

For better performance in production, queue your Scout operations:

This will queue all indexing operations, preventing API rate limits and improving response times.

Available Commands

This package provides custom commands for managing Vectorize indexes and metadata indexes, plus the standard Laravel Scout commands:

Vectorize Index Management

Options for vectorize:create-index:

Options for vectorize:drop-index:

Metadata Index Management

Arguments for vectorize:create-metadata-index:

Arguments for vectorize:delete-metadata-index:

Options for metadata index commands:

Standard Scout Commands

How It Works

  1. Indexing: When a model is indexed, the driver:

    • Calls toSearchableText() or flattens toSearchableArray() to text
    • Generates an embedding using Cloudflare Workers AI
    • Stores the vector in Cloudflare Vectorize with metadata
  2. Searching: When you search:

    • Your query text is converted to an embedding
    • Vectorize finds the most similar vectors
    • Results are mapped back to your Eloquent models
    • Models are fetched from your database and returned
  3. Vector IDs: The driver prefixes vector IDs with the model class name to support multiple model types in one index (e.g., App_Models_Product_123)

Limitations

Configuration Reference

Troubleshooting

Search returns no results

Indexing is slow

Errors about dimensions

Authentication errors

Metadata filtering not working

Performance optimization

Architecture

Package Structure

How Embeddings Work

This package uses Cloudflare Workers AI to generate embeddings:

  1. Text Preparation: Your model data is converted to text using toSearchableText() or by flattening toSearchableArray()
  2. Embedding Generation: The text is sent to Cloudflare Workers AI which returns a vector (array of floats)
  3. Vector Storage: The vector is stored in Vectorize along with metadata (model class and searchable data)
  4. Semantic Search: When you search, your query is also converted to a vector and compared against stored vectors using cosine similarity

Supported Embedding Models

Model Dimensions Best For
@cf/baai/bge-small-en-v1.5 384 Faster processing, lower memory
@cf/baai/bge-base-en-v1.5 768 Balanced (default)
@cf/baai/bge-large-en-v1.5 1024 Higher accuracy, slower

Vector ID Format

Vectors are stored with IDs in the format: {ModelClass}_{ModelKey}

Example: App_Models_Product_123

This allows multiple model types to coexist in the same Vectorize index.

Testing

The package includes comprehensive tests covering all engine functionality:

Test Coverage

The test suite includes 23+ tests covering:

Running Tests

Tests use Orchestra Testbench to simulate a Laravel environment and Mockery to mock the VectorizeClient, ensuring tests run without making actual API calls.

Best Practices

Optimizing Search Quality

  1. Use descriptive text: Include context in your searchable content

  2. Avoid overly long text: Embeddings work best with focused, relevant content

  3. Include relevant metadata: Add fields you'll filter on

Performance Tips

  1. Enable queueing for production: Prevent blocking requests

  2. Use batch operations: Import in bulk rather than one-by-one

  3. Limit search results: Only fetch what you need

  4. Cache frequent queries: Use Laravel's cache for popular searches

Security Considerations

  1. Sanitize user input: Always validate and sanitize search queries

  2. Protect API credentials: Never commit API tokens to version control

  3. Use scopes for access control: Filter by user permissions

Comparison with Other Search Solutions

Feature Vectorize (this package) Algolia Meilisearch Elasticsearch
Semantic Search ✅ Built-in ❌ Keyword only ⚠️ Limited ⚠️ Via plugins
Setup Complexity ⭐⭐ Easy ⭐ Very Easy ⭐⭐ Easy ⭐⭐⭐⭐ Complex
Cost 💰 Cloudflare pricing 💰💰💰 Premium 💰 Free/Cheap 💰💰 Moderate
Latency Fast (edge network) Very Fast Fast Moderate
Filtering ⚠️ Basic metadata ✅ Advanced ✅ Good ✅ Advanced
Typo Tolerance ❌ No ✅ Yes ✅ Yes ✅ Yes
Relevance by Keywords ❌ No ✅ Excellent ✅ Good ✅ Excellent
Relevance by Meaning ✅ Excellent ❌ No ⚠️ Limited ⚠️ Via plugins
Infrastructure Serverless Managed Self-host/Managed Self-host/Managed

When to Use Vectorize

Good fit:

Not ideal for:

FAQ

Q: Can I use multiple models in the same index? A: Yes! The driver automatically namespaces vectors by model class, so multiple models can coexist in one index.

Q: How accurate is semantic search compared to keyword search? A: Semantic search excels at understanding intent and meaning, but may miss exact keyword matches. Consider your use case.

Q: Can I migrate from Algolia/Meilisearch to Vectorize? A: Yes, but be aware that Vectorize uses semantic search, which behaves differently from keyword-based search engines.

Q: What happens if I change the embedding model? A: You'll need to create a new index with the correct dimensions and re-index all your data.

Q: Is there a limit on the number of vectors? A: Check Cloudflare's Vectorize pricing and limits for your account tier.

Q: Can I use this with multilingual content? A: Yes! The BGE embedding models support multiple languages and can find semantically similar content across languages.

Contributing

Contributions are welcome! Please submit pull requests or open issues on GitHub.

Development Setup

License

This package is open-source software licensed under the MIT license.

Credits

Support

For issues, questions, or contributions, please visit the GitHub repository.


All versions of laravel-scout-vectorize with dependencies

PHP Build Version
Package Version
Requires php Version ^8.1
illuminate/support Version ^10.0|^11.0|^12.0
laravel/scout Version ^10.0|^11.0
guzzlehttp/guzzle Version ^7.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package brynj-digital/laravel-scout-vectorize contains the following files

Loading the files please wait ...