diff --git a/src/Illuminate/Collections/Collection.php b/src/Illuminate/Collections/Collection.php index 65b9ec5f48b9..0e18e2c2a1d8 100644 --- a/src/Illuminate/Collections/Collection.php +++ b/src/Illuminate/Collections/Collection.php @@ -1056,25 +1056,31 @@ public function splitIn($numberOfGroups) * Get the first item in the collection, but only if exactly * item exists. Otherwise, throw an exception. * - * @param callable|null $callback + * @param mixed $key + * @param mixed $operator + * @param mixed $value * @return mixed * * @throws \Illuminate\Collections\ItemNotFoundException * @throws \Illuminate\Collections\MultipleItemsFoundException */ - public function sole(callable $callback = null) + public function sole($key = null, $operator = null, $value = null) { - $items = $this->when($callback)->filter($callback); + if (func_num_args() <= 1) { + $items = $this->when($key)->filter($key); - if ($items->isEmpty()) { - throw new ItemNotFoundException; - } + if ($items->isEmpty()) { + throw new ItemNotFoundException; + } + + if ($items->count() > 1) { + throw new MultipleItemsFoundException; + } - if ($items->count() > 1) { - throw new MultipleItemsFoundException; + return $items->first(); } - return $items->first(); + return $this->sole($this->operatorForWhere(...func_get_args())); } /** diff --git a/src/Illuminate/Collections/LazyCollection.php b/src/Illuminate/Collections/LazyCollection.php index be5a7d09602c..8046f3aa421b 100644 --- a/src/Illuminate/Collections/LazyCollection.php +++ b/src/Illuminate/Collections/LazyCollection.php @@ -1014,20 +1014,26 @@ public function split($numberOfGroups) * Get the first item in the collection, but only if exactly * item exists. Otherwise, throw an exception. * - * @param callable|null $callback + * @param mixed $key + * @param mixed $operator + * @param mixed $value * @return mixed * * @throws \Illuminate\Collections\ItemNotFoundException * @throws \Illuminate\Collections\MultipleItemsFoundException */ - public function sole(callable $callback = null) + public function sole($key = null, $operator = null, $value = null) { - return $this - ->when($callback) - ->filter($callback) - ->take(2) - ->collect() - ->sole(); + if (func_num_args() <= 1) { + return $this + ->when($key) + ->filter($key) + ->take(2) + ->collect() + ->sole(); + } + + return $this->sole($this->operatorForWhere(...func_get_args())); } /** diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 2f3544900403..f80f69a2236c 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -79,6 +79,8 @@ public function testSoleReturnsFirstItemInCollectionIfOnlyOneExists($collection) ]); $this->assertSame(['name' => 'foo'], $collection->where('name', 'foo')->sole()); + $this->assertSame(['name' => 'foo'], $collection->sole('name', '=', 'foo')); + $this->assertSame(['name' => 'foo'], $collection->sole('name', 'foo')); } /**