Day 2 – Tracking User Views and Preparing for AI Recommendations #LaravelGPT #ProductViewTracking #AIRecommender #UserBehavior #GPTFunctionCalling


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.

See also  Day 8 – Ask GPT: β€œWhat Changed Yesterday?” Using Natural Language#LaravelGPTAudit #AIAssistant #NaturalLanguageAudit #GPTFunctionCalling #LaravelLogs

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.