To reduce the number of queries and improve the efficiency of your index page, you can leverage eager loading and more complex queries to fetch the necessary data in fewer queries. Here's a revised approach:
- Eager Load Relationships: Use eager loading to reduce the number of queries when fetching related models.
- Single Query for Articles: Fetch all necessary articles in a single query and then group them in PHP.
Here's a revised version of your code:
public function index(Request $request, Hobby $hobby = null)
{
$categories = Tag::where('tag_type', 12)->whereNull('parent_id')->get();
$hobby_id = $hobby->id; // Assuming $hobby is the chosen hobby
// Get all necessary articles in a single query
$articlesQuery = $hobby->hobbyArticles()
->status('published')
->ArticleType('article')
->with(['categories' => function ($query) {
$query->whereNull('parent_id');
}])
->get([
'id', 'title', 'slug', 'pinned', 'premium_cost',
'view_count', 'user_id', 'post_as', 'group_id',
'published_on',
]);
// Separate pinned articles
$pinned = $articlesQuery->where('pinned', true)->sortByDesc('view_count')->take(5);
// Initialize articles collection
$articles = collect(['pinned' => $pinned]);
foreach ($categories as $category) {
// Filter articles by category
$categoryArticles = $articlesQuery->filter(function ($article) use ($category) {
return $article->categories->contains('id', $category->id);
});
// Get top 5 newest articles
$newest = $categoryArticles->sortByDesc('published_on')->take(5);
// Get top 5 most popular articles
$popular = $categoryArticles->sortByDesc('view_count')->take(5);
// Add the articles to the collection
$articles->put($category->tag, [
'newest' => $newest,
'popular' => $popular,
]);
}
return view('your-view', compact('articles'));
}
Explanation:
-
Eager Loading: The
with(['categories' => function ($query) { ... }])part ensures that the categories are loaded with the articles in a single query. -
Single Query for Articles: The
$articlesQueryfetches all necessary articles in one go. - Filtering and Sorting in PHP: After fetching all articles, we filter and sort them in PHP, which reduces the number of database queries.
Additional Tips:
- Caching: Implement caching to store the results of these queries, especially if the data doesn't change frequently. This will significantly reduce the load on your database.
-
Indexes: Ensure that your database tables are properly indexed, especially on columns used in
WHERE,ORDER BY, andJOINclauses.
By following this approach, you should be able to reduce the number of queries and improve the performance of your index page.