Skip to content
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

[5.5] Add whereNotIn() to Collection #18145

Closed
wants to merge 1 commit 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
31 changes: 29 additions & 2 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -393,13 +393,16 @@ public function whereStrict($key, $value)
* @param string $key
* @param mixed $values
* @param bool $strict
* @param bool $not
* @return static
*/
public function whereIn($key, $values, $strict = false)
public function whereIn($key, $values, $strict = false, $not = false)
{
$method = $not ? 'reject' : 'filter';

$values = $this->getArrayableItems($values);

return $this->filter(function ($item) use ($key, $values, $strict) {
return $this->$method(function ($item) use ($key, $values, $strict) {
return in_array(data_get($item, $key), $values, $strict);
});
}
Expand All @@ -416,6 +419,30 @@ public function whereInStrict($key, $values)
return $this->whereIn($key, $values, true);
}

/**
* Filter items by the given key value pair.
*
* @param string $key
* @param mixed $values
* @return static
*/
public function whereNotIn($key, $values)
{
return $this->whereIn($key, $values, false, true);
}

/**
* Filter items by the given key value pair using strict comparison.
*
* @param string $key
* @param mixed $values
* @return static
*/
public function whereNotInStrict($key, $values)
{
return $this->whereIn($key, $values, true, true);
}

/**
* Get the first item from the collection.
*
Expand Down
12 changes: 12 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,18 @@ public function testWhereInStrict()
$this->assertEquals([['v' => 1], ['v' => 3]], $c->whereInStrict('v', [1, 3])->values()->all());
}

public function testWhereNotIn()
{
$c = new Collection([['v' => 1], ['v' => 2], ['v' => 3], ['v' => '3'], ['v' => 4]]);
$this->assertEquals([['v' => 2], ['v' => 4]], $c->whereNotIn('v', [1, 3])->values()->all());
}

public function testWhereNotInStrict()
{
$c = new Collection([['v' => 1], ['v' => 2], ['v' => 3], ['v' => '3'], ['v' => 4]]);
$this->assertEquals([['v' => 2], ['v' => '3'], ['v' => 4]], $c->whereNotInStrict('v', [1, 3])->values()->all());
}

public function testValues()
{
$c = new Collection([['id' => 1, 'name' => 'Hello'], ['id' => 2, 'name' => 'World']]);
Expand Down