Today weβll track which products a user views, storing the data in the user_product_views
table. This view history will serve as the input context for our GPT-powered recommendations.
π§ Step 1: Define relationships
In User.php
:
public function viewedProducts()
{
return $this->belongsToMany(\App\Models\Product::class, 'user_product_views')
->withPivot('viewed_at')
->withTimestamps();
}
In Product.php
:
public function viewers()
{
return $this->belongsToMany(\App\Models\User::class, 'user_product_views')
->withPivot('viewed_at')
->withTimestamps();
}
π Step 2: Create a controller to simulate views
php artisan make:controller ProductViewController
In routes/web.php
:
use App\Http\Controllers\ProductViewController;
Route::get('/products/{id}/view', [ProductViewController::class, 'view'])->name('products.view');
In ProductViewController.php
:
use App\Models\Product;
use Illuminate\Support\Facades\Auth;
public function view($id)
{
$product = Product::findOrFail($id);
$user = Auth::user() ?? \App\Models\User::first(); // fallback for demo
$user->viewedProducts()->syncWithoutDetaching([
$product->id => ['viewed_at' => now()],
]);
return response()->json([
'message' => "Viewed: {$product->name}",
'product' => $product,
]);
}
π§ͺ Step 3: Simulate viewing some products
Visit in browser:
http://localhost:8000/products/1/view
http://localhost:8000/products/3/view
Check the view table:
php artisan tinker
>>> \App\Models\User::first()->viewedProducts
β You should see products returned based on the view history.
β Summary
You now:
- Log which products users interact with
- Store time-based views for later analysis
- Have clean data to feed into GPT for context-aware recommendations
β Up next (Day 3): weβll build a GPT function-calling setup that suggests new products based on this userβs view history.