I want to display only 3 news in each category to display the last 3 news that were added.
Class category:
class category extends Model
{
use HasFactory;
public function articles(){
return $this->hasMany(Article::class)->limit(3)->orderBy('created_at', 'desc');
}
}
Class Article:
class Article extends Model
{
use HasFactory;
public function category(){
return $this->belongsTo(category::class);
}
}
$categories = category::with('articles')->limit(3)->get();
$articles = Article::orderBy('created_at', 'desc')->get();
return response()->view('news.index', compact('categories','articles'));
2
Answers
use whereHas
By using latest()