Laravel Collection get unique values from nested datastructure
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
The Laravel Collection class offers a versatile set of methods and utilities for working with collections of data. One powerful method is unique, which helps eliminate duplicate values from a collection. Let's explore how to use this feature when dealing with nested objects in your Laravel projects.
Imagine you have the following data structure:
{
"key1": [
{"id": 1},
{"id": 1}
],
"key2": [
{"id": 1},
{"id": 2}
]
}In this case, you want to remove the duplicate ID 1 from the array under "key 1" while leaving all other values intact. Your current nested data structure makes it a bit tricky since Laravel's Collection's unique method doesn't directly support nested arrays. To tackle this issue, you have two options:
- Option 1: Flatten the Nested Structure and Apply Unique Method
- Option 2: Loop through Each Nested Array and Apply Unique Method Separately
Solution Code Snippet:
$input = $request->all();
$collection = collect($input);
foreach ($collection as &$item) {
// Flatten the nested array structure
if (is_array($item)) {
unset($item);
$item = array_merge(...$item);
}
}
$unique = $collection->unique('id');Solution Code Snippet:
$input = $request->all();
$collection = collect($input);
// Process nested arrays one by one
foreach ($collection as $key => $arr) {
if (is_array($arr)) {
$uniqueArr = $arr->unique('id');
if (!$uniqueArr->isEmpty()) {
$collection[$key] = $uniqueArr;
}
}
}In conclusion, Laravel's Collection class offers powerful tools like the unique method for working with collections of data. However, it isn't directly applicable to nested structures. By following the two provided solutions, you can effectively address this issue and achieve your desired output regardless of the depth or complexity of your nested data structure.
Note: If you are dealing with larger collections or more complex nesting levels, consider leveraging Laravel's Eloquent ORM for better performance. For additional resources and guidance on working with data structures in Laravel, visit our blog.