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