Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lakazai's avatar

Query Optimize Laravel (inRandomOrder, whereHas, search)

because my data is getting bigger. I have 3 queries that I want to optimize. the posts table currently has nearly 1 million rows. I use redis so I don't talk about query cache problem.

project info: laravel 8.x, mysql5.7, php7.4.x

1.I want to get 8 post related (by category) order random in post detail page.

index: posts.status, post_category.post_id, post_category.category_id unique: posts.slug,

$post = Post::where('status', Post::PUBLISHED)->where('slug', $slug)->with(['categories', 'tags'])->first();
if (!$post) {
    abort(404);
}
$cat_ids = $post->categories->pluck('id')->toArray();
$post_related = Post::where('status', Post::PUBLISHED)
    ->whereHas('categories', function ($q) use ($cat_ids) {
        $q->whereIn('categories.id', $cat_ids);
    })->inRandomOrder($post->id)->take(8)->get();

2.This is the category detail page.

index: posts.status, posts.count_views, post_category.post_id, post_category.category_id unique: posts.slug, categories.key

public function categoryDetail($key){
    $category = Category::where('key', $key)->first();
    if (!$category) {
        abort(404);
    }
    $post_category = Post::where('status', Post::PUBLISHED)
        ->whereHas('categories', function ($q) use ($key) {
            $q->where('key', $key);
        })->orderByDesc('count_views')->paginate(24);
    return ...
}

3.This is the search page. index: posts.status

public function search(Request $request)
{
    $type = $request->input('type');
    $search = $request->input('search');

    $data['posts'] = Post::where('status', Post::PUBLISHED)->where('title', 'like', "%$search%")->paginate(24);

    return view('home.search', $data);
}

thank you

0 likes
3 replies
lakazai's avatar

in this particular problem. Can you say more details. thank you

Please or to participate in this conversation.