2026-02-05 22:22:10 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
|
|
|
|
|
|
use App\Models\ContentViewLog;
|
|
|
|
|
use App\Models\Product;
|
|
|
|
|
use Illuminate\Http\Request;
|
|
|
|
|
|
|
|
|
|
class ProductController extends Controller
|
|
|
|
|
{
|
|
|
|
|
public function show(string $slug, Request $request)
|
|
|
|
|
{
|
|
|
|
|
$product = Product::with('tags', 'category')->where('slug', $slug)->firstOrFail();
|
|
|
|
|
|
|
|
|
|
$this->recordView($product, $request);
|
|
|
|
|
|
|
|
|
|
$comments = $product->comments()
|
|
|
|
|
->where('status', 'approved')
|
|
|
|
|
->orderByDesc('created_at')
|
|
|
|
|
->get();
|
|
|
|
|
|
|
|
|
|
$relatedProducts = Product::published()
|
|
|
|
|
->where('id', '!=', $product->id)
|
|
|
|
|
->whereHas('tags', function ($query) use ($product) {
|
|
|
|
|
$query->whereIn('tags.id', $product->tags->pluck('id'));
|
|
|
|
|
})
|
|
|
|
|
->orderByDesc('hot_score')
|
|
|
|
|
->limit(8)
|
|
|
|
|
->get();
|
|
|
|
|
|
2026-02-07 22:55:07 +08:00
|
|
|
return view('frontend.product.show', [
|
2026-02-05 22:22:10 +08:00
|
|
|
'product' => $product,
|
|
|
|
|
'comments' => $comments,
|
|
|
|
|
'relatedProducts' => $relatedProducts,
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function recordView(Product $product, Request $request): void
|
|
|
|
|
{
|
|
|
|
|
$ip = $request->ip() ?? '0.0.0.0';
|
|
|
|
|
$userAgent = $request->userAgent() ?? 'unknown';
|
|
|
|
|
$userAgentHash = sha1($userAgent);
|
|
|
|
|
|
|
|
|
|
$log = ContentViewLog::firstOrCreate([
|
|
|
|
|
'content_type' => 'product',
|
|
|
|
|
'content_id' => $product->id,
|
|
|
|
|
'ip' => $ip,
|
|
|
|
|
'user_agent_hash' => $userAgentHash,
|
|
|
|
|
'viewed_on' => now()->toDateString(),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
if ($log->wasRecentlyCreated) {
|
|
|
|
|
$product->increment('view_count');
|
|
|
|
|
$product->refreshHotScore();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|