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.
Related Tips
View all tips →Combine Multiple Arrays by Index with Collection::zip()
Use zip() on Laravel Collections to merge array elements sharing matching index positions into paired sub-collections.
Verify Entire Datasets with Collection::every()
Use every() on Laravel Collections to verify whether every single item in a collection satisfies a truth test.