Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jonnyso's avatar

How does the Collection "unique" function work under the hood ?

So, I've noticed that you can pass a callback to the unique function from Laravel, like so:

From de docs: https://laravel.com/docs/5.8/collections#method-unique

$unique = $collection->unique(function ($item) {
    return $item['brand'].$item['type'];
});

So it seems that you can basically concatenate the values of any combination of keys in your collection and it knows what to look for ?

Does it actually concatenate every combination until it finds a match ? I tried looking on the source code but couldn't figure it out.

0 likes
2 replies
mattsplat's avatar

Here's the code I found for it.

public function unique($key = null, $strict = false)
    {
        $callback = $this->valueRetriever($key);
        $exists = [];
        return $this->reject(function ($item, $key) use ($callback, $strict, &$exists) {
            if (in_array($id = $callback($item, $key), $exists, $strict)) {
                return true;
            }
            $exists[] = $id;
        });
    }

It looks like it determines if you have passed a callback or not. If you did it uses that if not it just creates a callback that returns the entire row. It then creates an empty array that will hold the response of the callback for each row. Then it loops through populating the array with the callback response if it doesn't exist. If it does exist it rejects that row.

So the response of your callback is all that matters .

Please or to participate in this conversation.