-
Notifications
You must be signed in to change notification settings - Fork 11.7k
[8.x] Add sole to the query builder #35869
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
- Loading branch information
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -3,6 +3,8 @@ | |
| namespace Illuminate\Database\Concerns; | ||
|
|
||
| use Illuminate\Container\Container; | ||
| use Illuminate\Database\MultipleRecordsFoundException; | ||
| use Illuminate\Database\NoRecordsFoundException; | ||
| use Illuminate\Pagination\LengthAwarePaginator; | ||
| use Illuminate\Pagination\Paginator; | ||
|
|
||
|
|
@@ -147,6 +149,30 @@ public function first($columns = ['*']) | |
| return $this->take(1)->get($columns)->first(); | ||
| } | ||
|
|
||
| /** | ||
| * Execute the query and get the first result if it's the sole. | ||
| * | ||
| * @param array|string $columns | ||
| * @return \Illuminate\Database\Eloquent\Model|object|static|null | ||
| * | ||
| * @throws \Illuminate\Database\NoRecordsFoundException | ||
| * @throws \Illuminate\Database\MultipleRecordsFoundException | ||
| */ | ||
| public function sole($columns = ['*']) | ||
| { | ||
| $result = $this->get($columns); | ||
|
||
|
|
||
| if ($result->isEmpty()) { | ||
| throw new NoRecordsFoundException(); | ||
| } | ||
|
|
||
| if ($result->count() > 1) { | ||
| throw new MultipleRecordsFoundException(); | ||
| } | ||
|
|
||
| return $result->first(); | ||
| } | ||
|
|
||
| /** | ||
| * Apply the callback's query changes if the given "value" is true. | ||
| * | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| <?php | ||
|
|
||
| namespace Illuminate\Database; | ||
|
|
||
| use RuntimeException; | ||
|
|
||
| class MultipleRecordsFoundException extends RuntimeException | ||
| { | ||
|
|
||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| <?php | ||
|
|
||
| namespace Illuminate\Database; | ||
|
|
||
| use RuntimeException; | ||
|
|
||
| class NoRecordsFoundException extends RuntimeException | ||
| { | ||
|
|
||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This simplifies to
object|null.