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

Nite's avatar
Level 1

Query Collection on nested item

Assume I have the following Eloquent query (Since I will use the returned collection in more than one place, I eager load the related model) :

$myModels = MyModel::with(['myRelatedModel'])->where(...) ... ->get();

Now, what if I want to query $myModels to return only the ones where a field of myRelatedModel is xyz ? In a normal Eloquent query I'd use whereHas, but on collections that is not available.

$results = $myModels->where ??

Thanks

0 likes
7 replies
mabdullahsari's avatar
Level 16

You can still do it using the db.

Model::with([
    'related' => fn ($query) => $query->where('xyz', 'abc')
])->get();
Nite's avatar
Level 1

@mabdullahsari The point was to avoid making another db query, and use the data from the collection I already have.

tykus's avatar

@Nite it'd likely be the more efficient option; depending on the sizes of the main and nested Collections. Iterating over large Collections in PHP would probably be more expensive.

2 likes
mabdullahsari's avatar

@Nite Processing done by the database is always cheaper than processing done in PHP.

1 like

Please or to participate in this conversation.