Skip to content

Commit

Permalink
Added a way to retrieve the first column of the first row from a quer…
Browse files Browse the repository at this point in the history
…y. (#41858)

* Added a way to retrieve the first column of the first row from a query result.

* styleci fixes
  • Loading branch information
peterlupu authored Apr 6, 2022
1 parent 8e4f4f7 commit efb174c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
27 changes: 27 additions & 0 deletions Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,33 @@ public function selectOne($query, $bindings = [], $useReadPdo = true)
return array_shift($records);
}

/**
* Run a select statement and return the first column of the first row.
*
* @param string $query
* @param array $bindings
* @param bool $useReadPdo
* @return mixed
*
* @throws MultipleColumnsSelectedException
*/
public function scalar($query, $bindings = [], $useReadPdo = true)
{
$record = $this->selectOne($query, $bindings, $useReadPdo);

if (is_null($record)) {
return null;
}

$record = (array) $record;

if (count($record) > 1) {
throw new MultipleColumnsSelectedException;
}

return reset($record);
}

/**
* Run a select statement against the database.
*
Expand Down
10 changes: 10 additions & 0 deletions MultipleColumnsSelectedException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Illuminate\Database;

use RuntimeException;

class MultipleColumnsSelectedException extends RuntimeException
{
//
}

0 comments on commit efb174c

Please sign in to comment.