how many category sections you have? I feel like with proper indexes loading 4-5 sections should not be that slow
How can I optimize repeated recipe queries for HomepageSections?
Hey everyone! I'm struggling with multiple SQL queries being executed when fetching homepage sections with recipes in my Laravel project.
In my HomeController index I load visible & ordered HomepageSection models, and then map each one to include related recipes using a custom getRecipes() method:
HomeController:
$homepageSections = HomepageSection::visible()->ordered()->get();
$sections = $homepageSections->map(function ($section){
return [
'id' => $section->slug,
'title' => $section->name,
'recipes' => $section->getRecipes(), // problem reason
'visible' => $section->visible,
'order' => $section->order,
];
});
The getRecipes() method loads recipes based on section type:
HomepageSection.php
$query = Recipe::with('dishCategory');
return match($this->type) {
'popular' => $query->popular()->limit($this->limit)->get(),
'latest' => $query->latest()->limit($this->limit)->get(),
'category' => $query->byCategory($this->category_slug)->limit($this->limit)->get(),
default => collect(),
};
The problem is: for every section of type category, the byCategory() scope triggers a separate query like this:
Recipe
public function scopeByCategory(Builder $query, string $categorySlug): Builder
{
return $query->whereHas('dishCategory', function ($q) use ($categorySlug) {
$q->where('slug', $categorySlug);
});
}
I tried caching recipes per section, but I feel like there must be a better way
Would be grateful for your help
Best regards
Please or to participate in this conversation.