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

CodeFox's avatar

Query Builder Issue

Hey,

I'm trying to build a small query module and have hit an issue. I read this article and have implemented something similar where I'm trying to search through a related model using Builder:

public function filter(Request $request, City $city)
    {
        $city = $city->newQuery();

        // Search for a city based on its state.
        if ($request->has('state')) {
            $city->whereHas('state', function ($query) use ($request) {
                $query->where('state', $request->state);
            });
        }

This doesn't trigger an error, it just returns an empty object.

0 likes
3 replies
tykus's avatar

Is state a relation on the City model; whereHas checks for the existence of a relation to scope the parent (City) query?

If state is a column on the cities table, then the query should be:

if ($request->has('state')) {
    $city->where('state', $request->state);
}
CodeFox's avatar

Hey @tykus

State is a relation on the City model, so this is intended. My City hasOne State.

tykus's avatar

Ok, and there is a state column in the states table which is the same type as the incoming $request->state?

Please or to participate in this conversation.