diff --git a/src/Illuminate/Collections/Collection.php b/src/Illuminate/Collections/Collection.php index 95faa17a7121..e0ea16b577f3 100644 --- a/src/Illuminate/Collections/Collection.php +++ b/src/Illuminate/Collections/Collection.php @@ -614,6 +614,29 @@ public function hasAny($key) return false; } + /** + * Determine if all keys exist in the collection. + * + * @param TKey|array $keys + * @return bool + * + * @throws \InvalidArgumentException + */ + public function hasAll($keys) + { + $keys = is_array($keys) ? $keys : func_get_args(); + + if (empty($keys)) { + throw new InvalidArgumentException('Keys must be provided.'); + } + + if ($this->isEmpty()) { + return false; + } + + return empty(array_diff($keys, array_keys($this->all()))); + } + /** * Concatenate values of a given key as a string. * diff --git a/src/Illuminate/Collections/LazyCollection.php b/src/Illuminate/Collections/LazyCollection.php index daf811bfcadd..c2628158fb33 100644 --- a/src/Illuminate/Collections/LazyCollection.php +++ b/src/Illuminate/Collections/LazyCollection.php @@ -627,6 +627,29 @@ public function hasAny($key) return false; } + /** + * Determine if all keys exist in the collection. + * + * @param TKey|array $keys + * @return bool + * + * @throws \InvalidArgumentException + */ + public function hasAll($keys) + { + $keys = is_array($keys) ? $keys : func_get_args(); + + if (empty($keys)) { + throw new InvalidArgumentException('Keys must be provided.'); + } + + if ($this->isEmpty()) { + return false; + } + + return empty(array_diff($keys, array_keys($this->all()))); + } + /** * Concatenate values of a given key as a string. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 513e1fa4187a..429c4e0cea7f 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -2357,6 +2357,25 @@ public function testHasAny($collection) $this->assertFalse($data->hasAny([])); } + #[DataProvider('collectionClassProvider')] + public function testHasAll($collection) + { + $data = new $collection(['id' => 1, 'first' => 'Hello', 'second' => 'World']); + + $this->assertTrue($data->hasAll('id')); + $this->assertTrue($data->hasAll('id', 'first', 'second')); + $this->assertFalse($data->hasAll('id', 'first', 'second', 'third')); + $this->assertTrue($data->hasAll(['id', 'first'])); + $this->assertTrue($data->hasAll(['first', 'second'])); + $this->assertFalse($data->hasAll(['third', 'fourth'])); + $this->assertFalse($data->hasAll('third', 'fourth')); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Keys must be provided.'); + + $data->hasAll([]); + } + #[DataProvider('collectionClassProvider')] public function testImplode($collection) {