Duplicate entries on updateOrCreate method

Posted 2 years ago by chimit

I want to save mobile devices information in the database using their unique identifiers. identifier field is unique. The code is:

$device = Device::updateOrCreate(
    ['identifier' => $request->input('identifier')],
        'model' => $request->input('model'),

But I'm getting a lot of errors in logs:

Next Doctrine\DBAL\Driver\PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'aa18269c-cf32-4c6b-b450-e84a5dba0a0c' for key 'devices_device_identifier_unique' in /var/www/api/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:93
Stack trace:

I also tried to use firstOrNew:

$device = Device::firstOrNew(['identifier' => $request->input('identifier')]);
$device->model = $request->input('model');

But it's equal I think.

If I remove the unique index from the identifier field the problem is gone but I get duplicate entries. That's strange because I thought updateOrCreate method guarantees uniqueness of the entries.

Maybe these devices are sending multiple requests at the same time, but is it possible that MySQL can't handle this common situation properly?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.