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

FounderStartup's avatar

How to write a Nested query in eloquent

I am developing a real estate portal.

The relationships are like this

City has many localities City has many buildings Building has many listings Building has one builder

How to show buildings of only enabled cities. What will be my eloquent query in the controller ? How to show builders of only enabled cities. How to show listings of only enabled cities.

Can I code something in Cities modal so that I need not change anywhere else in my code ?

Or kindly share a good article for the solution.

0 likes
4 replies
SilenceBringer's avatar

@founderstartup read the docs https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

assuming you have correct rrelationships between all the models, your queries will be like:

How to show buildings of only enabled cities

Building::whereHas('city', fn ($query) => $query->where('enabled', 1))

How to show builders of only enabled cities (nestead relationships)

Builder::whereHas('building.city', fn ($query) => $query->where('enabled', 1))

and so on

1 like
FounderStartup's avatar

@SilenceBringer

Thanks for your effort. I am getting following error :

ParseError syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ')'

Following is my controller code

$projects = projects::whereHas('city', fn ($query) => $query->where('status', 1))->orderBy('id','ASC')->paginate(15);

Following is my modal relation


  public function city(){
    	return $this->belongsTo(Cities::class,'project_city','id');
    }

Let me know the correct code if possible

SilenceBringer's avatar
Level 55

@FounderStartup it's because you have php version < 7.4 replace arrow function

$projects = projects::whereHas('city', function ($query) {
		return $query->where('status', 1);
})
	->orderBy('id','ASC')
	->paginate(15);
1 like
FounderStartup's avatar

Got it ....

$projects = projects::whereHas('city', function ($query) {
            $query->where('status', 1);
        })->orderBy('id','ASC')->paginate(15);

Now trying to get the next type.

Please or to participate in this conversation.