From 57b233d3dce17c38e062fd5327919fbf1f88f017 Mon Sep 17 00:00:00 2001 From: guidocella Date: Tue, 28 Feb 2017 09:10:53 +0100 Subject: [PATCH] Add whereNotIn to Collection --- src/Illuminate/Support/Collection.php | 31 +++++++++++++++++++++++-- tests/Support/SupportCollectionTest.php | 12 ++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index e5e94bf73e22..8f33f52048ad 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -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); }); } @@ -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. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index f0ab3ac1dcf3..29ac7613286a 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -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']]);