Laravel Collections

Identify and Extract Duplicate Values with Collection::duplicates()

Punyapal Shah 1 min read
edit this tip
Use duplicates() on Laravel Collections to quickly find and extract duplicate values or duplicate model attributes from a dataset.

When validating imported CSV spreadsheets, checking for duplicate emails in an array, or auditing datasets, filtering duplicates manually requires nested loops or array count checks.

The duplicates() method finds all duplicate items and returns their original array keys.

Basic Duplicate Detection

$emails = collect([
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]', // Duplicate
]);

$duplicates = $emails->duplicates();

// Output: [3 => '[email protected]']

Checking Duplicate Object Attributes

Pass a column name or key to check for duplicates inside object or associative collections:

$employees = collect([
    ['id' => 1, 'email' => '[email protected]'],
    ['id' => 2, 'email' => '[email protected]'],
    ['id' => 3, 'email' => '[email protected]'],
]);

$duplicateEmails = $employees->duplicates('email');

// Output: [2 => '[email protected]']

Summary

  • Returns a new collection containing only the duplicated values with their original keys.
  • Accepts key strings or closures to detect duplicate nested attributes.
  • Perfect for CSV import validation and batch data cleansing.
Tags: Laravel Collections Validation Data Transformation
Share on X

// Found an issue or want to contribute a tip? github.com/MrPunyapal/tips