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

Johny22's avatar

Query

Hi how could I retrieve data with such a query? The point is, I would need to save the category and country in as a result of filtering. He tried foreach but it didn't work. Need to call another function on the builder?

$categoryId = $request->get('category_id');
        $countryCod = $request->get('country_code');

        $country = Country::query()->with('categories')->where('country_code', '=',  $countryCod)
            ->whereHas('categories', function ($query) use ($categoryId) {
                return $query->where('id', $categoryId);
            });

0 likes
8 replies
MichalOravec's avatar

Actually I don't know what do you want. I just guess

$country = Country::with(['categories' => $closure = function ($query) use ($request) {
    return $query->where('id', $request->category_id);
}])->whereHas('categories', $closure)->where('country_code', $request->country_code)->first();

By the way you are from Slovakia right?

Johny22's avatar

Yes from Slovakia. I'm going to try it.

Johny22's avatar

This returned an error

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from countries where exists (select * from categories inner join country_category on categories.id = country_category.category_id where countries.id = country_category.country_id and id = 1) and country_code is null limit 1)

MichalOravec's avatar
Level 75
$country = Country::with(['categories' => $closure = function ($query) use ($request) {
    return $query->where('categories.id', $request->category_id);
}])->whereHas('categories', $closure)->where('country_code', $request->country_code)->first();
Johny22's avatar

Even if you could advise me how I could connect other relations services? When I add it to the function behind categories, it's an error

Johny22's avatar

And I made a typo going it's great thank you again

Please or to participate in this conversation.