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

FounderStartup's avatar

How to get correct nested eloquent query

I need to show total 'listings' in 'projects' of a 'builder'

$totallistings = App\Models\Listings::whereHas('project.builder', function ($query) {$query->where('id','$item->id');})->count();

listings is related to projects project is related to builder

Its giving nill count.

0 likes
9 replies
tisuchi's avatar

@founderstartup Have you tried without a quote in $item->id?

e.g.

$totallistings = App\Models\Listings::whereHas('project.builder', function ($query) use ($item) {
        $query->where('id', $item->id);
    })->count();
1 like
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

You also need to import $item to the scope

$totallistings = App\Models\Listings::whereHas('project.builder', function ($query) use ($item) {//here
        $query->where('id', $item->id);
    })->count(); 
1 like

Please or to participate in this conversation.