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

DuckHunter's avatar

Checking for Duplicates specific to one record

I'm looking for the cleanest way to do this. I have three tables: users, user_identifiers, and bans. bans and user_identifiers have foreign keys that reference a user. The user_identifiers table has an identifier_type column as well as a data column to differentiate between different types of identifiers. Each user has several identifiers.

I'm trying to figure out the best way to pull all of the identifiers of a particular user and check to see if they have any duplicate identifiers with other users (keeping in mind that data and type matters). If there are duplicate identifiers, I want to check to see if any of the users with matching identifiers are banned. If so, then I want to ban the current user.

I'd like to be able to do this completely using eloquent if possible and with minimal looping to optimize performance.

0 likes
2 replies
Tray2's avatar

I would make a unique constraint that covers the user_id, identifyer_type and the data, that way you can prevent that from happening.

The easiest way to check the existence of duplicates is to use the having count syntax

https://www.w3resource.com/sql/aggregate-functions/count-having.php

As a last option you can prevent you query from fetching duplicates by using distinct, but that is a last resort, since it slows the query down.

1 like
Snapey's avatar

you want to do this for ALL users, like a house keeping job, or only check the current user?

1 like

Please or to participate in this conversation.