init
This commit is contained in:
57
web10/app/Http/Controllers/ProductController.php
Normal file
57
web10/app/Http/Controllers/ProductController.php
Normal file
@@ -0,0 +1,57 @@
|
||||
<?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();
|
||||
|
||||
return view('product.show', [
|
||||
'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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user