im trying to get 4 categories with only 4 articles in laravel using this code:
$categoryArticles = Category::whereHas('articles')->with(['articles' => function($q){
$q->select('id', 'title')->take(4);
}])->take(4)->get();
but its returning empty artilces relation for some categories, the when i remove the take(4)
in relation, the code will work correctly:
$categoryArticles = Category::whereHas('articles')->with(['articles' => function($q){
$q->select('id', 'title');
}])->take(4)->get();
but i need to take only 4 article for each category.
what is the problem?
Article.php Model:
public function categories() {
return $this->belongsToMany(Category::class, 'article_category');
}
Category.php Model:
public function articles() {
return $this->belongsToMany(Article::class, 'article_category');
}