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

FounderStartup's avatar

What is the correct nested relationship query for filter page

I need to show list of builders on a page with selected city in dropdown filter.

Builder is related to project project is related to city

my controller

    public function SearchBuildersincity(Request $request){
        
        $city = $request->project_city;
        $builders = Builders::whereHas('project.city', function ($query) {
            $query->where('status', 1);
        })->whereHas('project', function ($query) {
            $query->where('project_city', $city);
        })->latest()->paginate(15)->withQueryString();

What will be the correct query ?

0 likes
4 replies
SilenceBringer's avatar
Level 55

@founderstartup added when to cover the case when city is not selected

		$builders = Builders::whereHas('project', fn ($query) =>
            $query->when($request->project_city, fn ($query, $city) => $query->where('project_city', $city))
				->whereHas('city', fn ($query) => $query->where('status', 1));
        )
			->latest()
			->paginate(15)
			->withQueryString();
1 like
FounderStartup's avatar

@SilenceBringer

What i exactly need is :

To show builders who have projects in the cities ( with status = 1 ) and city selected in the filter dropdown.

FounderStartup's avatar

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

this is the error I am getting

Please or to participate in this conversation.