simedkom/app/Livewire/Home/News/Index.php

76 lines
2.2 KiB
PHP

<?php
namespace App\Livewire\Home\News;
use App\Models\News;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;
use Spatie\Tags\Tag;
#[Title('Berita')]
class Index extends Component
{
use WithPagination;
#[Url(as: 'q')]
public $search = '';
#[Url(as: 'tag')]
public $tag = '';
public function updatedSearch()
{
$this->resetPage();
}
public function updatedTag()
{
$this->resetPage();
}
public function render()
{
$news = News::published()
->with('author')
->when($this->search, function ($query) {
$query->where('title', 'like', '%'.$this->search.'%')
->orWhere('content', 'like', '%'.$this->search.'%');
})
->when($this->tag, function ($query) {
$query->withAnyTags([$this->tag]);
})
->latest('published_at')
->paginate(5)
->through(function ($news) {
$news->thumbnail = $news->getFirstMediaUrl('news') ?: 'https://images.pexels.com/photos/12199409/pexels-photo-12199409.jpeg';
$news->formatted_date = $news->published_at?->translatedFormat('d F Y') ?: '-';
$news->author_name = $news->author?->name ?: 'Admin';
$news->formatted_views = number_format($news->views).' Views';
$news->excerpt = str($news->content)->stripTags()->limit(160);
return $news;
});
$popularPosts = News::published()
->latest('views')
->limit(3)
->get()
->map(function ($news) {
$news->thumbnail = $news->getFirstMediaUrl('news') ?: 'https://images.pexels.com/photos/12199409/pexels-photo-12199409.jpeg';
$news->formatted_date = $news->published_at?->translatedFormat('d F Y') ?: '-';
return $news;
});
return view('livewire.home.news.index', [
'pageTitle' => 'Berita',
'pageDescription' => 'Jelajahi berita terbaru seputar purwakarta.',
'news' => $news,
'popularPosts' => $popularPosts,
'tags' => Tag::all(),
]);
}
}