Laravel Daily's

Building Intelligent Semantic Search APIs with Laravel 13 and the Laravel AI SDK

hero image

Traditional search breaks when users misspell words or describe concepts instead of matching exact database columns. Keyword queries miss the intent behind the text. Semantic search solves this by comparing the meaning of words using vector embeddings.

Laravel 13 introduces native vector search support directly inside Eloquent. Paired with the first-party Laravel AI SDK and PostgreSQL, you can build production-grade search systems without installing external vector databases.

You get a complete set of php developer tools that integrate smoothly into your stack. Let's look at how to build an intelligent semantic search engine from scratch.

Prerequisites: PostgreSQL and pgvector

Vector search requires a database capable of storing and indexing high-dimensional numeric arrays. PostgreSQL with the pgvector extension provides a robust foundation for this.

On your self-hosted PostgreSQL instance, enable the extension through your database migrations using Laravel's built-in schema helpers.

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;

public function up(): void
{
    Schema::ensureVectorExtensionExists();

    Schema::table('documents', function (Blueprint $table) {
        $table->vector('embedding', dimensions: 1536)
              ->nullable()
              ->index();
    });
}

This creates a high-performance vector column directly on your table. You do not need complex third-party search microservices or separate synchronization pipelines.

Laravel AI Official Branding

Configuring the Laravel AI SDK

The Laravel AI SDK handles communication with embedding providers like OpenAI, Anthropic, or local models via Ollama. It gives you a unified syntax across different AI providers.

Configure your default embeddings driver in config/ai.php.

return [
    'default_for_embeddings' => 'openai',

    'providers' => [
        'openai' => [
            'driver' => 'openai',
            'key' => env('OPENAI_API_KEY'),
        ],
    ],
];

This setup keeps configuration minimal. You can switch AI providers by changing a single environment variable without rewriting your business logic.

Indexing Content and Generating Embeddings

Raw text needs conversion into numeric vectors before you can search by meaning. You generate these vectors whenever records are created or updated.

Use the Embeddings facade provided by the AI SDK to transform text into vectors.

use Laravel\AI\Facades\Embeddings;
use App\Models\Document;

public function storeDocument(string $title, string $body): Document
{
    $text = $title . ' ' . $body;

    $response = Embeddings::for([$text])->generate()->first();

    return Document::create([
        'title' => $title,
        'body' => $body,
        'embedding' => $response->embedding,
    ]);
}

Developer building a semantic search API

For high-traffic applications, dispatch this embedding generation into a background queued job. Keeping vector creation asynchronous ensures your write operations remain fast and responsive.

Building the REST API Endpoint

Now you can build rest api with php that accepts natural language queries and returns semantically relevant matches. Laravel 13 introduces the whereVectorSimilarTo() query builder method.

Create a controller endpoint that handles incoming search requests.

namespace App\Http\Controllers;

use App\Models\Document;
use Illuminate\Http\Request;

class SearchController extends Controller
{
    public function __invoke(Request $request)
    {
        $validated = $request->validate([
            'query' => 'required|string|max:255',
        ]);

        $results = Document::whereVectorSimilarTo(
                column: 'embedding',
                value: $validated['query'],
                minSimilarity: 0.78
            )
            ->take(10)
            ->get();

        return response()->json([
            'data' => $results,
        ]);
    }
}

When you pass a plain string to whereVectorSimilarTo(), Laravel automatically converts that query string into an embedding using your configured AI provider. It then performs cosine similarity calculations inside PostgreSQL, returning records ordered by semantic relevance.

As a foundational php web framework, Laravel handles the heavy lifting behind the scenes. You write expressive, readable code while leveraging advanced machine learning primitives.

Performance and HNSW Indexing

As your document table grows into millions of rows, exact vector scans become slow. PostgreSQL and pgvector support HNSW (Hierarchical Navigable Small World) indexes to accelerate similarity searches.

Add an HNSW index to your vector column in a migration.

public function up(): void
{
    Schema::table('documents', function (Blueprint $table) {
        $table->vectorIndex('embedding', algorithm: 'hnsw');
    });
}

This indexing strategy keeps query response times lightning-fast even at scale. You get enterprise-grade search performance without leaving your primary database.

Minimalist Laravel Arc

Conclusion

Semantic search used to require specialized search engines and complicated data synchronization scripts. Laravel 13 brings vector search directly into Eloquent, simplifying your architecture.

Combine PostgreSQL, the Laravel AI SDK, and the whereVectorSimilarTo query builder to ship intelligent features faster. Give these tools a try in your next application, and let us know what you build.

Previous
Building Resilient SPAs: Error Handling with Inertia 3.x's Rescue Slots and Polling Modes
Next
Supercharge Your Inertia Workflow: DevTools Extension + Laravel LSP Are Here