To find duplicates in a Laravel collection, you can use the duplicates()
method.
The duplicates
method retrieves and returns duplicate values from the collection:
For Example:
$collection = collect(['a', 'b', 'a', 'c', 'b']);
$collection->duplicates();
// [2 => 'a', 4 => 'b']
If the collection contains arrays or objects, you can pass the key of the attributes that you wish to check for duplicate values:
$employees = collect([
['email' => 'alice@example.com', 'position' => 'Developer'],
['email' => 'bob@example.com', 'position' => 'Designer'],
['email' => 'charlie@example.com', 'position' => 'Developer'],
]);
$employees->duplicates('position');
// [2 => 'Developer']
You can also find duplicates in a Laravel collection by using the countBy
method in combination with the filter method.
The countBy
method will group the items in the collection by a given key and return a new collection with the counts of each group. You can then use the filter
method to keep only the groups with a count greater than 1.
Here’s an example:
$collection = collect([
['name' => 'Alice', 'email' => 'alice@example.com'],
['name' => 'Bob', 'email' => 'bob@example.com'],
['name' => 'Charlie', 'email' => 'charlie@example.com'],
['name' => 'Charlie', 'email' => 'charlie@example.com'],
]);
$duplicates = $collection->countBy('email')
->filter(function ($count) {
return $count > 1;
});
// $duplicates is now a collection containing ['charlie@example.com' => 2]
The countBy
method will return a collection with the key being the value of the given key and the value being the count.
You can then use the keys
method to get an array of the duplicated values:
$duplicateEmails = $duplicates->keys();
// $duplicateEmails is now ['charlie@example.com']
Note that the countBy
method will only work if you want to find duplicates based on a specific key. If you want to find duplicates based on the values of the items in the collection, you can use a different approach.
One way to do this is to use the combine
method in combination with the flatten
and unique
methods:
$collection = collect([
['name' => 'Alice', 'email' => 'alice@example.com'],
['name' => 'Bob', 'email' => 'bob@example.com'],
['name' => 'Charlie', 'email' => 'charlie@example.com'],
['name' => 'Charlie', 'email' => 'charlie@example.com'],
]);
$duplicates = $collection->combine($collection->flatten())
->unique(null, true)
->filter(function ($count) {
return $count > 1;
});
// $duplicates is now a collection containing ['charlie@example.com' => 2]
This will create a new collection with the values as keys and the items as values, then use the unique
method to remove the unique items, and finally use the filter
method to keep only the items with a count greater than 1.