laravel eloquent ignore error when inserting a duplicate key

laravel eloquent ignore error when inserting a duplicate key

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling Duplicate Keys in Laravel Eloquent Without Crashing

When migrating data from an external service or processing a bulk JSON feed, you often encounter scenarios where the dataset changes between runs. You might have a strict unique constraint on your primary key to prevent duplicates, but you don't want the entire batch insert to fail just because some records already exist in the database. The standard DB::table()->insert() method throws an exception immediately upon hitting a duplicate key violation, which stops the transaction and leaves partial data behind.

To solve this in Laravel without removing your unique constraint or switching to a less strict storage engine like MyISAM, you need to leverage the specific error codes returned by the database driver. Most relational databases, including MySQL, return a specific error code (1062 for duplicate entry) when a unique violation occurs. Laravel's query builder allows you to catch this exception and handle it gracefully, effectively skipping the problematic rows while continuing with the rest of the batch.

Catching the Duplicate Key Exception

The most direct approach involves wrapping your insert logic in a try-catch block that specifically targets the Illuminate\Database\QueryException. Within the exception handler, you can inspect the error code to determine if it is indeed a duplicate key issue before deciding whether to log it or ignore it.

Here is how you can structure this logic for a batch insert:

use Illuminate\Support\Facades\DB;
use Illuminate\Database\QueryException;

$data = [
    ['id' => 1, 'name' => 'one'],
    ['id' => 2, 'name' => 'two'],
    ['id' => 3, 'name' => 'three'],
];

try {
    DB::table('dummy')->insert($data);
} catch (QueryException $e) {
    // Check if the error is specifically a duplicate key violation
    if ($e->errorInfo[1] === 1062) {
        // Log the specific rows causing issues or handle them individually
        // In many cases, simply swallowing this exception achieves the goal of "ignoring" duplicates
        return; 
    }

    // Re-throw unexpected database errors
    throw $e;
}

This pattern ensures that if a duplicate key is found on the first row (like id: 1), Laravel throws an exception, you catch it, verify it's a duplicate, and then exit. The rows processed before the failure were already written to the database in the same transaction context, assuming no other errors occurred previously.

Switching to Batch Processing for Better Control

While catching the exception works for a single batch operation, relying on exceptions to control flow is generally considered an anti-pattern in high-frequency scripts because it prevents you from knowing exactly which rows were skipped versus which ones succeeded without additional logic. A more robust strategy involves iterating through the data or using upsert methods if your goal is strictly "insert or update."

However, if your requirement is strictly to insert new records and ignore those that already exist (without updating them), you can implement a manual loop. This gives you granular control over logging skipped entries:

$recordsToInsert = [];

foreach ($jsonPayload as $item) {
    // Check if the record exists first using 'where'
    $exists = DB::table('dummy')->where('id', $item['id'])->exists();
    
    if (!$exists) {
        $recordsToInsert[] = $item;
    } else {
        // Optionally log that this ID was skipped
        // Log::info("Skipping duplicate ID: {$item['id']}");
    }
}

// Perform the insert only on unique records
if (!empty($recordsToInsert)) {
    DB::table('dummy')->insert($recordsToInsert);
}

Trade-offs and Performance Considerations

Choosing between catching exceptions and pre-checking existence involves a performance trade-off. The exists() query adds an O(n) read operation before the insert, which can significantly slow down bulk loads for large datasets due to additional round-trips to the database. Conversely, relying on the exception handler is faster in terms of I/O but risks partial data if the application crashes mid-batch after the first duplicate is encountered.

If you are working with very large datasets and need to ensure idempotency (running the script multiple times with identical results), pre-checking existence or using Laravel's upsert() method might be preferable. However, upsert() will update existing records if they match the key, which violates your requirement of keeping unique constraints without altering data.

For simple scripts where speed is paramount and you accept that the script must be idempotent by design (i.e., it does nothing on second runs), catching the 1062 error code remains a lightweight solution that avoids unnecessary reads. Always ensure you are handling the exception specifically for your target table and not letting generic database errors slip through, as they could mask critical issues with foreign keys or column types.

For deeper insights into managing database transactions and query optimization in Laravel, you can refer to resources like https://laravelcompany.com.

Our network