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

FarhadMohammadi's avatar

Laravel Eloquent Query Optimization

How to optimize this query? Is this a good query or not? if not how to optimize it?

    return $query->whereHas('orderItem', function ($query) {
        return $query->whereHas('order', function ($query) {
              return $query->whereHas('context', function ($query) {
                   return $query->where('doctor_id', $this->doctorId);
            });
        });
    });
0 likes
3 replies
Tray2's avatar
Tray2
Best Answer
Level 73

If you want optimize it, you should get the SQL the query generates, and run it with EXPLAIN to see if you need to add some indexes.

I would say it's a messy query, that I have no idea what it does, so to make it readable I would probably make a database view out of it and make it look something like

$result = ModelView::where('doctor_id', $this->doctorId)->get();
1 like
FarhadMohammadi's avatar

@Tray2 nice man thank you, Is it better to use query builder for this or Eloquent is OK? I mean whereHas is not so best practice at all right?

Tray2's avatar

@FarhadMohammadi Eloquent is just a syntactic sugar for the query builder, they both in the end boils down to SQL.

1 like

Please or to participate in this conversation.