From 4d4040b601b9e5eb469af8c221c372abd8e9948a Mon Sep 17 00:00:00 2001 From: Guido Cella Date: Wed, 1 Mar 2017 15:39:45 +0100 Subject: [PATCH] Add whereNotIn() to Collection (#18157) --- src/Illuminate/Support/Collection.php | 29 +++++++++++++++++++++++++ tests/Support/SupportCollectionTest.php | 12 ++++++++++ 2 files changed, 41 insertions(+) diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 0eef56bede69..f403da1313e2 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -416,6 +416,35 @@ 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 + * @param bool $strict + * @return static + */ + public function whereNotIn($key, $values, $strict = false) + { + $values = $this->getArrayableItems($values); + + return $this->reject(function ($item) use ($key, $values, $strict) { + return in_array(data_get($item, $key), $values, $strict); + }); + } + + /** + * 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->whereNotIn($key, $values, true); + } + /** * Get the first item from the collection. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index a99d2b1477a9..dba37e491ede 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -397,6 +397,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']]);