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

Let's avatar
Level 4

With Eloquent, how to filter with 2 fields (ids) ?

Hi,

I have 3 tables:

  • Images
  • Countries
  • Cities

A row in the table Images has 2 specific fields:

  • country_id
  • city_id

With my setup, I can get all images by a given country like this

Country::where('name', $country_name)->first()->images

And I can get all images by a given city like this

City::where('name', $city_name)->first()->images

With Eloquent, how can I get all images by country AND city ? (Without using PHP loops or Query Builder)

0 likes
7 replies
Let's avatar
Level 4

In my case, cities and countries are not related.

What I want is an "Eloquent representation" of this SQL query :

select * from images where country_id = XXX and city_id = YYY

Is there any built-in (and simpler) way to achieve it other than this:

$country = Country::where('name', $country_name)->first();
$city = City::where('name', $city_name)->first();
Image::where('country_id', $country->id)->where('city_id', $city->id);
tykus's avatar

Your Eloquent models are probably singular rather than plural:

Image::where('city_id', $city_id)->where('country_id', $country_id)->get();
bestmomo's avatar

Eloquent way :

Images::whereHas('country', function ($query) use($country_id) {
    $query->where('country_id, $country_id);
})->whereHas('city', function ($query) use($city_id) {
    $query->where('city_id, $city_id);
})->get();
tykus's avatar

@bestmomo your query is way too complex and not correct for what was requested. The query I gave will build the exact query that was asked for.

Let's avatar
Level 4

Okay,

I was looking for something like bellow, but I guess a such function doesn't exist?

Image::whereForeign('countries', 'name', $country_name)->whereForeign('cities', 'name', $city_name);
bestmomo's avatar

@tykus_ikus : the question is how to do with Eloquent, there is no simpler way with it, and why do you say it's not correct ?

tykus's avatar

@bestmomo sorry, you're right - I completely misread the OP's needs (^_^)

my apologies

Please or to participate in this conversation.