Skip to content

Commit

Permalink
[9.x] Let Multiple* exceptions hold the number of records and items f…
Browse files Browse the repository at this point in the history
…ound (#41164)

* Let Multiple* exceptions hold the number of records and items found.

* formatting

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
lucasmichot and taylorotwell authored Feb 22, 2022
1 parent cee9ac4 commit 3df8c39
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 7 deletions.
8 changes: 5 additions & 3 deletions Concerns/BuildsQueries.php
Original file line number Diff line number Diff line change
Expand Up @@ -309,12 +309,14 @@ public function sole($columns = ['*'])
{
$result = $this->take(2)->get($columns);

if ($result->isEmpty()) {
$count = $result->count();

if ($count === 0) {
throw new RecordsNotFoundException;
}

if ($result->count() > 1) {
throw new MultipleRecordsFoundException;
if ($count > 1) {
throw new MultipleRecordsFoundException($count);
}

return $result->first();
Expand Down
8 changes: 5 additions & 3 deletions Eloquent/Relations/Relation.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,12 +171,14 @@ public function sole($columns = ['*'])
{
$result = $this->take(2)->get($columns);

if ($result->isEmpty()) {
$count = $result->count();

if ($count === 0) {
throw (new ModelNotFoundException)->setModel(get_class($this->related));
}

if ($result->count() > 1) {
throw new MultipleRecordsFoundException;
if ($count > 1) {
throw new MultipleRecordsFoundException($count);
}

return $result->first();
Expand Down
32 changes: 31 additions & 1 deletion MultipleRecordsFoundException.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,35 @@

class MultipleRecordsFoundException extends RuntimeException
{
//
/**
* The number of records found.
*
* @var int
*/
public $count;

/**
* Create a new exception instance.
*
* @param int $count
* @param int $code
* @param \Throwable|null $previous
* @return void
*/
public function __construct($count, $code = 0, $previous = null)
{
$this->count = $count;

parent::__construct("$count records were found.", $code, $previous);
}

/**
* Get the number of records found.
*
* @return int
*/
public function getCount()
{
return $this->count;
}
}

0 comments on commit 3df8c39

Please sign in to comment.