simedkom/app/Http/Controllers/Home/NewsController.php

84 lines
2.8 KiB
PHP

<?php
namespace App\Http\Controllers\Home;
use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\News;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Inertia\Inertia;
class NewsController extends Controller
{
public function index(Request $request)
{
$search = $request->get('search');
$category = $request->get('category');
$news = News::with(['author', 'categories'])
->published()
->when($search, function ($query, $search) {
$query->where(function ($q) use ($search) {
$q->where('title', 'like', "%{$search}%")
->orWhere('content', 'like', "%{$search}%")
->orWhere('excerpt', 'like', "%{$search}%");
});
})
->when($category, function ($query, $category) {
if ($category !== 'all') {
$query->whereHas('categories', function ($q) use ($category) {
$q->where('categories.id', $category);
});
}
})
->orderBy('published_at', 'desc')
->paginate(12)
->withQueryString()
->through(function ($news) {
$news->thumbnail = $news->getFirstMediaUrl('news');
$news->formatted_published_at = Carbon::parse($news->published_at)
->locale('id')
->translatedFormat('l, d F Y');
return $news;
});
$mostViewedNews = News::with(['author', 'categories'])
->published()
->orderBy('views', 'desc')
->take(4)
->get()
->map(function ($news) {
$news->thumbnail = $news->getFirstMediaUrl('news');
$news->formatted_published_at = Carbon::parse($news->published_at)
->locale('id')
->translatedFormat('l, d F Y');
return $news;
});
return Inertia::render('home/news/pages/Index', [
'pageTitle' => 'Berita',
'pageDescription' => 'Dapatkan informasi terbaru, artikel, dan update berita terkini tentang Purwakarta.',
'categories' => Category::active()->get(),
'news' => $news,
'mostViewedNews' => $mostViewedNews,
'filters' => request()->only(['search', 'category']),
]);
}
public function show(News $news)
{
$news->load(['author', 'categories', 'tags']);
$news->increment('views');
$news->thumbnail = $news->getFirstMediaUrl('news');
return Inertia::render('home/news/pages/Show', [
'pageTitle' => 'Detail Berita',
'pageDescription' => $news->title,
'news' => $news,
]);
}
}