Laravel Daily's

Building an AI-Powered Recommendation Engine with Laravel

hero image

Modern applications need intelligent discovery features. Traditional keyword searches often miss user intent. Semantic search and vector embeddings solve this gap. You can now build a robust recommendation engine directly inside your favorite php web framework.

The first-party Laravel AI SDK provides provider-agnostic tools for embeddings and vector queries. You no longer need external microservices for basic machine learning pipelines. Everything runs inside your application core.

Preparing the Database for Vector Search

Vector search requires storage capable of handling multi-dimensional arrays. PostgreSQL combined with pgvector provides native vector operations. MySQL does not support native vector queries out of the box.

Configure your database connection to use PostgreSQL. Create a migration with a vector column for your items.

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('description');
            $table->vector('embedding', dimensions: 1536);
            $table->timestamps();
        });
    }
};

Database Vector Storage

This setup prepares your database schema for high-performance similarity matching. Modern php developer tools make managing these database structures straightforward. You keep all your relational data and vector attributes in a single location.

Generating Embeddings with Laravel AI SDK

Embeddings translate text into numeric vectors that capture semantic meaning. Similar concepts yield vectors close to each other in vector space. The Laravel AI SDK streamlines this generation process.

Use the toEmbeddings() method on Laravel's Stringable class. You can switch between OpenAI, Anthropic, or local providers seamlessly.

namespace App\Console\Commands;

use App\Models\Product;
use Illuminate\Console\Command;

class IndexProducts extends Command
{
    protected $signature = 'products:index';

    public function handle(): void
    {
        Product::chunk(100, function ($products) {
            foreach ($products as $product) {
                $text = $product->name . ' ' . $product->description;
                
                $embedding = str($text)->toEmbeddings();

                $product->update([
                    'embedding' => $embedding->toArray(),
                ]);
            }
        });

        $this->info('Product embeddings generated successfully.');
    }
}

Run this command as a background job to process large catalogs efficiently. The framework handles API communication and rate limiting reliably.

Building Content-Based Recommendations

Content recommendations suggest items similar to the one a user currently inspects. Laravel's Eloquent query builder includes native vector comparison methods. Call whereVectorSimilarTo() on your model.

Product Recommendations

Implement the recommendation logic inside your product service class.

namespace App\Services;

use App\Models\Product;
use Illuminate\Database\Eloquent\Collection;

class RecommendationService
{
    public function getSimilarProducts(Product $product, int $limit = 6): Collection
    {
        $queryText = $product->name . ' ' . $product->description;

        return Product::whereKeyNot($product->id)
            ->whereVectorSimilarTo('embedding', $queryText)
            ->limit($limit)
            ->get();
    }
}

Laravel automatically generates an embedding for the query text. It executes an optimized distance calculation inside the database engine. You receive a ranked collection of semantically related records instantly.

Exposing Recommendations via a REST API

Frontends and mobile apps consume recommendation data asynchronously. You need clean endpoints to serve these items. Laravel makes it effortless to build rest api with php.

Create a dedicated controller to expose your recommendation endpoints.

namespace App\Http\ControllersApi;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Services\RecommendationService;
use Illuminate\Http\JsonResponse;

class ProductRecommendationController extends Controller
{
    public function __construct(
        protected RecommendationService $recommendations
    ) {}

    __(string $show, Product $product): JsonResponse
    {
        $items = $this->recommendations->getSimilarProducts($product);

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

REST API Endpoint

Register this route in your routes/api.php file.

use App\Http\ControllersApi\ProductRecommendationController;

Route::get('/products/{product}/recommendations', [ProductRecommendationController::class, 'show']);

Your API consumers now have instant access to AI-powered item matching. The response structure remains clean and ready for consumption by JavaScript frameworks or mobile clients.

Personalizing User Discovery

You can extend this architecture beyond single-item lookups. Aggregate user activity history into a preference summary string. Pass that summary into the vector query builder.

public function getPersonalizedFeed(User $user, int $limit = 10): Collection
{
    $summary = $user->browsingHistoryText();

    return Product::whereVectorSimilarTo('embedding', $summary)
        ->limit($limit)
        ->get();
}

Semantic matching bridges terminology gaps. Users discover relevant items even when their search terms differ from product titles.

Wrapping Up

Building intelligent features no longer requires complex microservice architectures. Laravel provides everything you need to implement vector search and embeddings natively.

Start experimenting with vector columns in your next application. We would love to hear what you build with these tools.

Previous
Supercharge Your Inertia Workflow: DevTools Extension + Laravel LSP Are Here
Next
Human-in-the-Loop for Laravel AI Agents: Stopping Dangerous Tool Calls Before They Fire