Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/Relation.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\MultipleRecordsFoundException;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Arr;
use Illuminate\Support\Traits\ForwardsCalls;
Expand Down Expand Up @@ -151,6 +153,30 @@ public function getEager()
return $this->get();
}

/**
* Execute the query and get the first result if it's the sole matching record.
*
* @param array|string $columns
* @return \Illuminate\Database\Eloquent\Model
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws \Illuminate\Database\MultipleRecordsFoundException
*/
public function sole($columns = ['*'])
{
$result = $this->take(2)->get($columns);

if ($result->isEmpty()) {
throw (new ModelNotFoundException)->setModel(get_class($this->model));
}

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

return $result->first();
}

/**
* Execute the query as a "select" statement.
*
Expand Down
14 changes: 14 additions & 0 deletions tests/Database/DatabaseEloquentIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -805,6 +805,20 @@ public function testHasOnMorphToRelationship()
$this->assertEquals(1, $photos->count());
}

public function testBelongsToManyRelationshipModelsAreProperlyHydratedWithSoleQuery()
{
$user = EloquentTestUserWithCustomFriendPivot::create(['email' => 'taylorotwell@gmail.com']);
$user->friends()->create(['email' => 'abigailotwell@gmail.com']);

$user->friends()->get()->each(function ($friend) {
$this->assertTrue($friend->pivot instanceof EloquentTestFriendPivot);
});

$soleFriend = $user->friends()->where('email', 'abigailotwell@gmail.com')->sole();

$this->assertTrue($soleFriend->pivot instanceof EloquentTestFriendPivot);
}

public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverChunkedRequest()
{
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
Expand Down