SYS://VISION.ACTIVE
VIEWPORT.01
LAT 28.0222° N
SIGNAL.NOMINAL
VISION Loading
Back to Blog

Building Recommendation Systems: AI-Powered Personalization

Shane Barron

Shane Barron

Laravel Developer & AI Integration Specialist

The Power of Personalization

Recommendation systems drive engagement on major platforms. Building your own connects users with relevant content, products, or features they might otherwise miss.

Collaborative Filtering Basics

class CollaborativeFilter
{
    public function findSimilarUsers(User $user, int $limit = 10): Collection
    {
        $userRatings = $user->ratings->pluck('rating', 'product_id');

        return User::where('id', '!=', $user->id)
            ->with('ratings')
            ->get()
            ->map(function ($otherUser) use ($userRatings) {
                $similarity = $this->cosineSimilarity(
                    $userRatings,
                    $otherUser->ratings->pluck('rating', 'product_id')
                );
                return ['user' => $otherUser, 'similarity' => $similarity];
            })
            ->sortByDesc('similarity')
            ->take($limit);
    }

    private function cosineSimilarity(Collection $a, Collection $b): float
    {
        $common = $a->keys()->intersect($b->keys());
        if ($common->isEmpty()) return 0;

        $dotProduct = $common->sum(fn ($id) => $a[$id] * $b[$id]);
        $magnitudeA = sqrt($common->sum(fn ($id) => $a[$id] ** 2));
        $magnitudeB = sqrt($common->sum(fn ($id) => $b[$id] ** 2));

        return $dotProduct / ($magnitudeA * $magnitudeB);
    }
}

Content-Based Recommendations

class ContentBasedRecommender
{
    public function recommend(User $user, int $limit = 10): Collection
    {
        // Get user preferences from history
        $preferences = $this->extractPreferences($user);

        // Find similar products
        return Product::query()
            ->whereNotIn('id', $user->purchasedProducts->pluck('id'))
            ->get()
            ->map(function ($product) use ($preferences) {
                $similarity = $this->calculateSimilarity($product, $preferences);
                return ['product' => $product, 'score' => $similarity];
            })
            ->sortByDesc('score')
            ->take($limit);
    }
}

AI-Enhanced Recommendations

class AIRecommender
{
    public function getRecommendations(User $user): array
    {
        $context = $this->buildUserContext($user);

        $prompt = <<getProductCatalog()}

Return recommendations as JSON with product IDs and reasoning.
PROMPT;

        return json_decode($this->ai->generate($prompt), true);
    }

    private function buildUserContext(User $user): string
    {
        return collect([
            'Recent Purchases' => $user->recentPurchases->pluck('name'),
            'Browsing History' => $user->browsingHistory->pluck('name'),
            'Wishlist' => $user->wishlist->pluck('name'),
            'Preferences' => $user->preferences,
        ])->toJson();
    }
}

Hybrid Approach

class HybridRecommender
{
    public function recommend(User $user): Collection
    {
        $collaborative = $this->collaborative->recommend($user, 20);
        $contentBased = $this->contentBased->recommend($user, 20);
        $aiEnhanced = $this->ai->recommend($user);

        // Combine and deduplicate
        return collect()
            ->merge($collaborative->map(fn ($r) => [...$r, 'source' => 'collaborative']))
            ->merge($contentBased->map(fn ($r) => [...$r, 'source' => 'content']))
            ->merge($aiEnhanced->map(fn ($r) => [...$r, 'source' => 'ai']))
            ->unique('product.id')
            ->sortByDesc('score')
            ->take(10);
    }
}

Conclusion

Effective recommendations combine multiple approaches. Start with collaborative filtering for behavior-based suggestions, add content-based for cold start problems, and enhance with AI for nuanced personalization.

Share this article
Shane Barron

Shane Barron

Strategic Technology Architect with 40 years of experience building production systems. Specializing in Laravel, AI integration, and enterprise architecture.

Need Help With Your Project?

I respond to all inquiries within 24 hours. Let's discuss how I can help build your production-ready system.

Get In Touch