diff --git a/src/Illuminate/Database/Eloquent/Builder.php b/src/Illuminate/Database/Eloquent/Builder.php index 2f0c2fed57db..3beb4c8c89ff 100755 --- a/src/Illuminate/Database/Eloquent/Builder.php +++ b/src/Illuminate/Database/Eloquent/Builder.php @@ -110,6 +110,7 @@ class Builder implements BuilderContract 'max', 'min', 'raw', + 'rawValue', 'sum', 'toSql', ]; diff --git a/src/Illuminate/Database/Query/Builder.php b/src/Illuminate/Database/Query/Builder.php index 59f45d27acd9..c7acc43e5f83 100755 --- a/src/Illuminate/Database/Query/Builder.php +++ b/src/Illuminate/Database/Query/Builder.php @@ -2596,6 +2596,20 @@ public function value($column) return count($result) > 0 ? reset($result) : null; } + /** + * Get a single expression value from the first result of a query. + * + * @param string $expression + * @param array $bindings + * @return mixed + */ + public function rawValue(string $expression, array $bindings = []) + { + $result = (array) $this->selectRaw($expression, $bindings)->first(); + + 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. * diff --git a/tests/Database/DatabaseQueryBuilderTest.php b/tests/Database/DatabaseQueryBuilderTest.php index 6a0b6d97c231..d876ab332c3b 100755 --- a/tests/Database/DatabaseQueryBuilderTest.php +++ b/tests/Database/DatabaseQueryBuilderTest.php @@ -2464,6 +2464,15 @@ public function testValueMethodReturnsSingleColumn() $this->assertSame('bar', $results); } + public function testRawValueMethodReturnsSingleColumn() + { + $builder = $this->getBuilder(); + $builder->getConnection()->shouldReceive('select')->once()->with('select UPPER("foo") from "users" where "id" = ? limit 1', [1], true)->andReturn([['UPPER("foo")' => 'BAR']]); + $builder->getProcessor()->shouldReceive('processSelect')->once()->with($builder, [['UPPER("foo")' => 'BAR']])->andReturn([['UPPER("foo")' => 'BAR']]); + $results = $builder->from('users')->where('id', '=', 1)->rawValue('UPPER("foo")'); + $this->assertSame('BAR', $results); + } + public function testAggregateFunctions() { $builder = $this->getBuilder();