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

colinlongworth's avatar

Tracing what is causing duplicates?

I appreciate this is a 'how long is a piece of string' question, but I want to make sure I'm not missing something obvious or whether there is another way to tackle / investigate this.

I have a Student model that occasionally has duplicate rows. I've reviewed all the updateOrCreate statements, and they appear to be correct i.e. If a student with a given email exists, update them, otherwise create. There are no other methods in use for creating students.

However, all duplicates have the same email.

Besides logging the SQL statements being made, is there any good methodology for tracing this behaviour?

0 likes
8 replies
Sinnbeck's avatar

It would be best if we can check your logic ourselves :)

colinlongworth's avatar

@Sinnbeck

Student::updateOrCreate(
                    [
                        'email' => '[email protected]'
                    ],
                    [
                        'first_name' => 'Joe'
                        'last_name' =>  'Blogs'
                    ]);

They all operate like this.

However, I have found a job with a unique ID that could cause a job duplication and hence a duplicate record, but it's clutching at straws.

Sinnbeck's avatar

@colinlongworth maybe make the email column unique. That way you will get an error when it tries and you can see where the error comes from

colinlongworth's avatar

@Sinnbeck Yeah, I think that's the best course of action here but I think I'll need to merge the existing duplicates first or the migration will fail given the existing duplicates.

Sinnbeck's avatar

And when it's unique you can switch to real upsert. That's way better and prevent race conditions

colinlongworth's avatar

@Tray2 Ohhh, now there is a possibility. I'll need to comb over the records and see.

Is a mutator/accessor pair the best way to combat this?

Please or to participate in this conversation.