20

I want to use Laravel 5.1 Collection's Unique method to filter unique IDs from nested objects.

Given the data structure

{
  "key1": [
    {"id": 1},
    {"id": 1}
  ],
  "key2": [
    {"id": 1},
    {"id": 2}
  ]
}

I want to return the same datastructure with duplicate id 1 removed from "key 1".

I wanted to use $unique = $collection->unique('id');, but this doesn't seem to apply to a nested datastructure as I have.

So I thought to use $collection

    $input = $request->all();

    $collection = collect($input);

    $collection->each(function($obj, $key) {
        //$key is "key1", "key2"
        //obj is the associated array of objects containing IDs
    })->unique('id');

I don't quite know how to structure this.

The result structure should be:

{
  "key1": [
    {"id": 1}
  ],
  "key2": [
    {"id": 1},
    {"id": 2}
  ]
}

5 Answers 5

31
$collection = $collection->map(function ($array) {
    return collect($array)->unique('id')->all();
});
Sign up to request clarification or add additional context in comments.

Comments

10

If your data structure is nested a single level, be it arrays or objects, simple

$unique = $collection->unique('key')

does the job.

Comments

3

if you have numeric List then you can use this code

$dataList = [1,2,4,5,3,2,1,98,1,2,4,5,6];

$dataList  = collect( $dataList )->unique();

you will get all the unique list.

[1,2,4,5,3,98,6]

2 Comments

You will get a collection with keys: Illuminate\Support\Collection {#4033 all: [0 => 1,1 => 2,2 => 4,3 => 5,4 => 3,7 => 98,12 => 6, ],}
solved by this way
0

This should also work, assuming I understood your question correctly and you're just trying to use the innermost value as your unique reference

$unique = $collection->unique('key.id')

Comments

0

You could also try the following.

$unique = collect($input)->unique('*.id');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.