Today we’ll integrate GPT function calling into Laravel to generate product recommendations based on the user’s viewing history.
🧠 Step 1: Set up OpenAI
Install the SDK:
composer require openai-php/laravel
Publish config:
php artisan vendor:publish --provider="OpenAI\Laravel\ServiceProvider"
In .env
, add your key:
OPENAI_API_KEY=sk-...
🧰 Step 2: Create the GPT service
php artisan make:service ProductRecommendationService
Inside app/Services/ProductRecommendationService.php
:
namespace App\Services;
use OpenAI\Laravel\Facades\OpenAI;
use App\Models\User;
class ProductRecommendationService
{
public function recommend(User $user): string
{
$viewed = $user->viewedProducts()
->latest('pivot_viewed_at')
->limit(5)
->get(['name', 'description', 'category'])
->map(fn ($p) => [
'name' => $p->name,
'description' => $p->description,
'category' => $p->category,
])
->toArray();
$function = [
'name' => 'suggest_products',
'description' => 'Suggest relevant products for a user based on viewed products',
'parameters' => [
'type' => 'object',
'properties' => [
'suggestions' => [
'type' => 'array',
'items' => ['type' => 'string'],
],
],
'required' => ['suggestions'],
],
];
$response = OpenAI::chat()->create([
'model' => 'gpt-4-0613',
'messages' => [
[
'role' => 'user',
'content' => 'Suggest products based on this viewing history: ' . json_encode($viewed),
],
],
'functions' => [$function],
'function_call' => ['name' => 'suggest_products'],
]);
$funcResult = $response['choices'][0]['message']['function_call']['arguments'] ?? '{}';
$decoded = json_decode($funcResult, true);
return $decoded['suggestions'] ?? [];
}
}
🚀 Step 3: Add route to get AI suggestions
In web.php
:
use App\Services\ProductRecommendationService;
Route::get('/recommendations', function (ProductRecommendationService $service) {
$user = \App\Models\User::first(); // demo
$suggestions = $service->recommend($user);
return response()->json([
'suggested_products' => $suggestions,
]);
});
✅ Output Example
Call:
http://localhost:8000/recommendations
Response:
{
"suggested_products": [
"Noise-Cancelling Earbuds",
"Gaming Chair",
"Adjustable Monitor Arm"
]
}
✅ Up next (Day 4): We’ll match GPT’s suggestions against real products in your DB and show them in a user-facing recommendation UI.