yalcin
php artisan make:component Widgets/NewsBox
Bu iki tane dosya oluşturacak: app/View/Widgets/NewsBox.php ve resources/views/components/widgets/news-box.blade.php.
app/View/Widgets/NewsBox.php:
<?php
namespace App\View\Components;
use App\Models\News;
use Illuminate\View\Component;
class NewsBox extends Component
{
public function __construct(
public int $limit = 10,
public ?string $tags = null
)
{
}
public function render()
{
$news = News::when($this->tags, function ($query, $tags) {
$tags = explode(',', $tags);
$query->whereHas('tags', function ($query) use ($tags) {
$query->whereIn('slug', $tags);
});
})
->latest()
->take($this->limit)
->get();
return view('components.widgets.news-box', compact('news'));
}
}
resources/views/components/widgets/news-box.blade.php:
@if($news)
<div class="news-box">
<ul>
@foreach($news as $newsItem)
<li>
<a href="{{ route('news.show', $newsItem->slug) }}">
<span>{{ $newsItem->title }}</span>
<small>{{ $newsItem->published_at->format('d.m.Y H:i') }}</small>
</a>
</li>
@endforeach
</ul>
</div>
@endif
Kullanmak istediğiniz yerde artık şöyle kullanabilirsiniz:
<div class="sidebar">
{{-- Varsayılan ayarlar (son 10 haberi gösterir) --}}
<x-widgets.news-box/>
{{-- Son 5 haberi gösterir --}}
<x-widgets.news-box limit="5"/>
{{-- futbol ve spor etiketlerine sahip son 5 haberi gösterir --}}
<x-widgets.news-box limit="5" tags="spor,futbol"/>
</div>
https://laravel.com/docs/8.x/blade#components