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

movepixels's avatar

Distinct Query

I am trying to query distinct, but because of the params conditions I am getting duplicate records for a user.

Situation: User has Profile and the profile can be listed under many areas (cities) via areas_profile pivot table. So a user ( Say Johnny) can be listed in Los Angeles, and Long Beach, so if a regular user clicks Los Angeles presto Johnny is listed there, same with Long Beach. All is good.

Problem: User clicks on California it pulls all the area_id's for California and pulls all profiles for anyone in California. Johnny is listed under both. So this query below works up-to a certain point. Johnny appears once in the California records as expected.

$users = DB::table('profiles')
            ->join('area_profiles', 'profiles.id', '=', 'area_profiles.profile_id')
            ->join('photos', 'profiles.id', '=', 'photos.profile_id')
            ->select($fields)
            ->whereIn('area_profiles.area_id', $parent)
            ->where('area_profiles.active', true)
            ->where('profiles.completed', true)
            ->where('photos.sort', 1)
            ->distinct()
            ->get();

But if Johnny says he is visiting Los Angeles and has a date selected area_profiles.travel is true for 1 record and false for the Long Beach record making them no longer distinct. So Johnny's profile appears twice under California.

How can I make it so that no matter what the profile_id, no matter what the conditions are make Johnny distinct?

Or after the find remove all duplicate profiles where the id is the same?

Thanks,

Dave

0 likes
3 replies
Tray2's avatar

You should be able to use ->first() to get the first record. That might solve your issue.

movepixels's avatar

I went with ->unique collection.

Works as needed :)

Thanks.

Please or to participate in this conversation.