Noqta
  • Home
  • Services
  • About us
  • Writing
  • Sign in
writing/tutorial/2024/05
● TutorialMay 19, 2024·10 min read

Enhancing User Experience with AI-Powered Recommendations in Laravel

Discover how AI-powered recommendations in Laravel can transform user experiences, boost engagement, and drive conversions in your web applications.

Anis Marrouchi
Anis Marrouchi
Author
·EN · FR · AR

In today's competitive digital landscape, providing a superior user experience can set your web application apart. One powerful way to enhance user experience is through AI-powered recommendations. This feature helps personalize the user interaction, making your site more engaging and user-friendly. In this tutorial, we will explore how to implement AI-powered recommendations in a Laravel application using Google Recommendations AI.

Introduction

Artificial Intelligence (AI) has drastically improved the way we tailor content and product recommendations to users. In this guide, we leverage AI to create an intelligent recommendation system in Laravel using Google Recommendations AI.

Explore the power of AI-driven recommendations to enhance user engagement on your website. Learn more here.

Prerequisites

Before you start, ensure you have the following prerequisites:

  • Basic understanding of Laravel framework
  • PHP installed on your local machine
  • Composer installed
  • Basic understanding of REST APIs and JSON
  • Google Cloud account with Recommendations AI enabled

Step 1: Setting Up Laravel Project

First, let's start by setting up a new Laravel project.

composer create-project --prefer-dist laravel/laravel recommendation-system
cd recommendation-system
php artisan serve

These commands will create a new Laravel project named recommendation-system and start the development server.

Step 2: Set Up Google Recommendations AI

  1. Enable Recommendations AI in Google Cloud:

    Follow the instructions in the Google Cloud documentation to enable Recommendations AI.

  2. Set up authentication:

    Download your service account key file from the Google Cloud Console and set the GOOGLE_APPLICATION_CREDENTIALS environment variable:

 export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/service-account-file.json"
  1. Install Google Cloud client library:

    Add the Google Cloud client library to your Laravel project:

    composer require google/cloud-recommendations-ai

Step 3: Integrate Google Recommendations AI

  1. Create a service to interact with Recommendations AI:
// app/Services/GoogleRecommendationService.php
namespace App\Services;
 
use Google\Cloud\RecommendationEngine\V1beta1\UserEventServiceClient;
use Google\Cloud\RecommendationEngine\V1beta1\PredictRequest;
use Google\Cloud\RecommendationEngine\V1beta1\PredictionApiKeyRegistryClient;
use Google\Cloud\RecommendationEngine\V1beta1\PredictResponse;
use Illuminate\Support\Facades\Log;
 
class GoogleRecommendationService
{
    protected $eventServiceClient;
    protected $apiKey;
 
    public function __construct()
    {
        $this->eventServiceClient = new UserEventServiceClient();
        $this->apiKey = env('GOOGLE_RECOMMENDATION_API_KEY');
    }
 
    public function getRecommendations($userId, $pageSize = 5)
    {
        $formattedParent = $this->eventServiceClient->placementName(
            'your-project-id',
            'global',
            'catalogs/default_catalog',
            'eventStores/default_event_store',
            'placements/product_detail'
        );
 
        $predictionClient = new PredictionApiKeyRegistryClient();
        $response = $predictionClient->predict(
            $formattedParent,
            ['userId' => $userId],
            ['pageSize' => $pageSize]
        );
 
        return $response->getResults();
    }
}

Step 4: Creating Models and Migrations

Define the data structures to store user activities and product details:

  1. Create a migration for activities and products tables:
php artisan make:migration create_activities_table
php artisan make:migration create_products_table
  1. Define the structure of activities migration:
// database/migrations/xxxx_xx_xx_create_activities_table.php
Schema::create('activities', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('user_id');
    $table->unsignedBigInteger('product_id');
    $table->timestamp('created_at');
});
  1. Define the structure of products migration:
// database/migrations/xxxx_xx_xx_create_products_table.php
Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->text('description');
    $table->decimal('price', 8, 2);
    $table->timestamp('created_at');
});

Run the migrations to create the tables:

php artisan migrate

Step 5: Fetching Recommendations

Create a controller to fetch the recommendations:

// app/Http/Controllers/RecommendationController.php
namespace App\Http\Controllers;
 
use App\Services\GoogleRecommendationService;
use Illuminate\Http\Request;
 
class RecommendationController extends Controller
{
    protected $recommendationService;
 
    public function __construct(GoogleRecommendationService $recommendationService)
    {
        $this->recommendationService = $recommendationService;
    }
 
    public function show($userId)
    {
        $recommendations = $this->recommendationService->getRecommendations($userId);
        return response()->json($recommendations);
    }
}

Define API routes for fetching recommendations:

// routes/api.php
Route::get('/recommendations/{user}', [App\Http\Controllers\RecommendationController::class, 'show']);

Step 6: Displaying Recommendations

  1. Create a view to display recommendations:

    <!-- resources/views/recommendations.blade.php -->
    <!DOCTYPE html>
    <html>
    <head>
        <title>Product Recommendations</title>
    </head>
    <body>
        <h1>Recommended Products</h1>
        <ul id="recommendations"></ul>
     
        <script>
            async function fetchRecommendations(userId) {
                const response = await fetch(`/api/recommendations/${userId}`);
                const recommendations = await response.json();
                const recommendationList = document.getElementById('recommendations');
                
                recommendations.forEach(product => {
                    const li = document.createElement('li');
                    li.textContent = product.name;
                    recommendationList.appendChild(li);
                });
            }
     
            fetchRecommendations(1);
        </script>
    </body>
    </html>

Conclusion

With these steps, you now have a functional AI-powered recommendation system integrated within your Laravel application using Google Recommendations AI. By personalizing the content shown to users, you can significantly enhance user engagement and satisfaction.

For in-depth insights and additional customization options, check the official Laravel documentation.

We hope this tutorial has been helpful in guiding you through the process of implementing AI-powered recommendations in Laravel. Remember, integrating AI solutions requires thoughtful planning to best meet your user needs. Happy coding!

● Tags
#AI#Web Development#Cloud Computing#Intermediate#10 min read
● Share
● A question?

Talk to a Noqta agent about this article.

Anis Marrouchi
Anis Marrouchi
Author · noqta
Follow ↗

● Read next

Accelerate Your App Success: Building and Running with Firebase
● Tutorial

Accelerate Your App Success: Building and Running with Firebase

May 23, 2024
Getting Started with ALLaM-7B-Instruct-preview
● Tutorial

Getting Started with ALLaM-7B-Instruct-preview

Apr 20, 2025
An Introduction to GPT-4o and GPT-4o mini
● Tutorial

An Introduction to GPT-4o and GPT-4o mini

Jul 23, 2024
Noqta
Terms and Conditions · Privacy Policy
Services
  • AI Automation
  • AI Agents
  • CX Automation
  • Vibe Coding
  • Project Management
  • Quality Assurance
  • Web Development
  • API Integration
  • Business Applications
  • Maintenance
  • Low-Code/No-Code
Links
  • About Us
  • How It Works?
  • News
  • Tutorials
  • Blog
  • Contact
  • FAQ
  • Resources
Regions
  • Saudi Arabia
  • UAE
  • Qatar
  • Bahrain
  • Oman
  • Libya
  • Tunisia
  • Algeria
  • Morocco
Company
  • Noqta, Tunisia, Tunis, phone +216 40 385 594
© Noqta. All rights reserved.