input('lang'); $cacheKey = 'blog_homepage_v2_' . ($lang ?: 'all'); // Bypass cache during testing so factory states remain immediate if (app()->environment('testing')) { return response()->json($this->fetchHomepageData($lang), 200); } $data = Cache::remember($cacheKey, 120, function () use ($lang) { return $this->fetchHomepageData($lang); }); return response()->json($data, 200); } private function fetchHomepageData(?string $lang): array { $latestPosts = Post::with(['category', 'tags', 'author']) ->byLanguage($lang) ->orderByDesc('published_at') ->take(5) ->get(); $latestCategories = Category::byLanguage($lang) ->orderByDesc('created_at') ->take(5) ->get(); $mostViewedPosts = Post::with(['category', 'tags', 'author']) ->byLanguage($lang) ->orderByDesc('views') ->take(5) ->get(); // High-performance random post selection: Avoids costly MySQL `ORDER BY RAND()` $candidateIds = Post::byLanguage($lang)->pluck('id'); $randomIds = $candidateIds->count() > 4 ? $candidateIds->random(4)->all() : $candidateIds->all(); $randomPosts = ! empty($randomIds) ? Post::with(['category', 'tags', 'author'])->whereIn('id', $randomIds)->get() : collect(); return [ 'latest_posts' => PostResource::collection($latestPosts)->resolve(), 'latest_categories' => CategoryResource::collection($latestCategories)->resolve(), 'most_viewed_posts' => PostResource::collection($mostViewedPosts)->resolve(), 'random_posts' => PostResource::collection($randomPosts)->resolve(), ]; } }