From 1846fb3e88818cfd3ec78150666a51295feddf7d Mon Sep 17 00:00:00 2001 From: Matthew Hailwood Date: Mon, 7 Mar 2022 14:28:38 +1300 Subject: [PATCH] Add soleValue method to query builders --- src/Illuminate/Database/Eloquent/Builder.php | 14 ++++++++++++++ src/Illuminate/Database/Query/Builder.php | 16 ++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/Illuminate/Database/Eloquent/Builder.php b/src/Illuminate/Database/Eloquent/Builder.php index 89865f308a7f..830f54f860f7 100755 --- a/src/Illuminate/Database/Eloquent/Builder.php +++ b/src/Illuminate/Database/Eloquent/Builder.php @@ -614,6 +614,20 @@ public function value($column) } } + /** + * Get a single column's value from the first result of a query if it's the sole matching record. + * + * @param string|\Illuminate\Database\Query\Expression $column + * @return mixed + * + * @throws \Illuminate\Database\Eloquent\ModelNotFoundException<\Illuminate\Database\Eloquent\Model> + * @throws \Illuminate\Database\MultipleRecordsFoundException + */ + public function soleValue($column) + { + return $this->sole([$column])->{Str::afterLast($column, '.')}; + } + /** * Get a single column's value from the first result of the query or throw an exception. * diff --git a/src/Illuminate/Database/Query/Builder.php b/src/Illuminate/Database/Query/Builder.php index 598a3cdab001..ab0a573ad2ec 100755 --- a/src/Illuminate/Database/Query/Builder.php +++ b/src/Illuminate/Database/Query/Builder.php @@ -2516,6 +2516,22 @@ public function value($column) return count($result) > 0 ? reset($result) : null; } + /** + * Get a single column's value from the first result of a query if it's the sole matching record. + * + * @param string $column + * @return mixed + * + * @throws \Illuminate\Database\RecordsNotFoundException + * @throws \Illuminate\Database\MultipleRecordsFoundException + */ + public function soleValue($column) + { + $result = (array) $this->sole([$column]); + + return reset($result); + } + /** * Execute the query as a "select" statement. *