I am showing a list of categories, and the article count within each category. I get the expected result, but I am having the N+1 problem.
My CategoriesController
index function:
public function index()
{
return View::make('categories.index', [
'articleCategories' => Category::where('type', 'articles')->orderBy('name')->get(),
]);
}
The Category
model has many relationship to articles:
public function articles()
{
return $this->hasMany('Article');
}
My categories.index
view:
@foreach($articleCategories as $articleCategory)
<p>
{{ HTML::link(URL::route('articles.category', array('category' => Str::slug($articleCategory->name))), $articleCategory->name) }}
{{ $articleCategory->articles->count() }}
</p>
@endforeach
Edit: It works if I eager load all related articles, but since I only need the article count pr category this seems overkill. Will eager loading articles and do ->count()
impact performance? Or is this the best way to do it?