2026-02-05 22:22:10 +08:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
|
|
|
|
|
|
use App\Models\Article;
|
|
|
|
|
use App\Models\ContentViewLog;
|
|
|
|
|
use App\Models\SiteSetting;
|
|
|
|
|
use Illuminate\Http\Request;
|
|
|
|
|
|
|
|
|
|
class ArticleController extends Controller
|
|
|
|
|
{
|
|
|
|
|
public function index(Request $request)
|
|
|
|
|
{
|
|
|
|
|
$perPage = (int) SiteSetting::value('article_page_size', 10);
|
|
|
|
|
$tagSlug = $request->query('tag');
|
|
|
|
|
|
|
|
|
|
$query = Article::published()->orderByDesc('published_at');
|
|
|
|
|
if ($tagSlug) {
|
|
|
|
|
$query->whereHas('tags', function ($tagQuery) use ($tagSlug) {
|
|
|
|
|
$tagQuery->where('slug', $tagSlug);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$articles = $query->paginate($perPage);
|
|
|
|
|
|
2026-02-07 22:55:07 +08:00
|
|
|
return view('frontend.article.index', [
|
2026-02-05 22:22:10 +08:00
|
|
|
'articles' => $articles,
|
|
|
|
|
'tagSlug' => $tagSlug,
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public function show(string $slug, Request $request)
|
|
|
|
|
{
|
|
|
|
|
$article = Article::with('tags')->where('slug', $slug)->firstOrFail();
|
|
|
|
|
|
|
|
|
|
$this->recordView($article, $request);
|
|
|
|
|
|
|
|
|
|
$comments = $article->comments()
|
|
|
|
|
->where('status', 'approved')
|
|
|
|
|
->orderByDesc('created_at')
|
|
|
|
|
->get();
|
|
|
|
|
|
|
|
|
|
$relatedArticles = Article::published()
|
|
|
|
|
->where('id', '!=', $article->id)
|
|
|
|
|
->whereHas('tags', function ($query) use ($article) {
|
|
|
|
|
$query->whereIn('tags.id', $article->tags->pluck('id'));
|
|
|
|
|
})
|
|
|
|
|
->orderByDesc('published_at')
|
|
|
|
|
->limit(6)
|
|
|
|
|
->get();
|
|
|
|
|
|
2026-02-07 22:55:07 +08:00
|
|
|
return view('frontend.article.show', [
|
2026-02-05 22:22:10 +08:00
|
|
|
'article' => $article,
|
|
|
|
|
'comments' => $comments,
|
|
|
|
|
'relatedArticles' => $relatedArticles,
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private function recordView(Article $article, Request $request): void
|
|
|
|
|
{
|
|
|
|
|
$ip = $request->ip() ?? '0.0.0.0';
|
|
|
|
|
$userAgent = $request->userAgent() ?? 'unknown';
|
|
|
|
|
$userAgentHash = sha1($userAgent);
|
|
|
|
|
|
|
|
|
|
$log = ContentViewLog::firstOrCreate([
|
|
|
|
|
'content_type' => 'article',
|
|
|
|
|
'content_id' => $article->id,
|
|
|
|
|
'ip' => $ip,
|
|
|
|
|
'user_agent_hash' => $userAgentHash,
|
|
|
|
|
'viewed_on' => now()->toDateString(),
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
if ($log->wasRecentlyCreated) {
|
|
|
|
|
$article->increment('view_count');
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|