Skip to content

[5.2] Make Collection unique method to use strict check when comparing keys #14451

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/Illuminate/Database/Eloquent/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,12 +160,13 @@ public function intersect($items)
* Return only unique items from the collection.
*
* @param string|callable|null $key
* @param bool $strict
* @return static
*/
public function unique($key = null)
public function unique($key = null, $strict = false)
{
if (! is_null($key)) {
return parent::unique($key);
return parent::unique($key, $strict);
}

return new static(array_values($this->getDictionary()));
Expand Down
7 changes: 4 additions & 3 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1020,9 +1020,10 @@ public function transform(callable $callback)
* Return only unique items from the collection array.
*
* @param string|callable|null $key
* @param bool $strict
* @return static
*/
public function unique($key = null)
public function unique($key = null, $strict = false)
{
if (is_null($key)) {
return new static(array_unique($this->items, SORT_REGULAR));
Expand All @@ -1032,8 +1033,8 @@ public function unique($key = null)

$exists = [];

return $this->reject(function ($item) use ($key, &$exists) {
if (in_array($id = $key($item), $exists)) {
return $this->reject(function ($item) use ($key, $strict, &$exists) {
if (in_array($id = $key($item), $exists, $strict)) {
return true;
}

Expand Down
36 changes: 36 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,42 @@ public function testUnique()
$this->assertEquals([[1, 2], [2, 3], [3, 4]], $c->unique()->values()->all());
}

public function testUniqueWithKeys()
{
$c = new Collection([
[
'id' => '0',
'name' => 'zero',
],
[
'id' => '00',
'name' => 'double zero',
],
[
'id' => '0',
'name' => 'again zero',
],
]);

$this->assertEquals([
[
'id' => '0',
'name' => 'zero',
],
[
'id' => '00',
'name' => 'double zero',
],
], $c->unique('id', true)->all());

$this->assertEquals([
[
'id' => '0',
'name' => 'zero',
],
], $c->unique('id')->all());
}

public function testUniqueWithCallback()
{
$c = new Collection([
Expand Down