Skip to content
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

[11.x] Add Eloquent\Collection::findOrFail #52690

Merged
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
31 changes: 31 additions & 0 deletions src/Illuminate/Database/Eloquent/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,37 @@ public function find($key, $default = null)
return Arr::first($this->items, fn ($model) => $model->getKey() == $key, $default);
}

/**
* Find a model in the collection by key or throw an exception.
*
* @param mixed $key
* @return TModel
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function findOrFail($key)
{
$result = $this->find($key);

if (is_array($key) && count($result) === count(array_unique($key))) {
return $result;
} elseif (! is_array($key) && ! is_null($result)) {
return $result;
}

$exception = new ModelNotFoundException;

if (! $model = head($this->items)) {
throw $exception;
}

$ids = is_array($key) ? array_diff($key, $result->modelKeys()) : $key;

$exception->setModel(get_class($model), $ids);

throw $exception;
}

/**
* Load a set of relationships onto the collection.
*
Expand Down
54 changes: 54 additions & 0 deletions tests/Database/DatabaseEloquentCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Collection as BaseCollection;
use LogicException;
use Mockery as m;
Expand Down Expand Up @@ -202,6 +203,59 @@ public function testFindMethodFindsManyModelsById()
$this->assertEquals([2, 3], $c->find([2, 3, 4])->pluck('id')->all());
}

public function testFindOrFailFindsModelById()
{
$mockModel = m::mock(Model::class);
$mockModel->shouldReceive('getKey')->andReturn(1);
$c = new Collection([$mockModel]);

$this->assertSame($mockModel, $c->findOrFail(1));
}

public function testFindOrFailFindsManyModelsById()
{
$model1 = (new TestEloquentCollectionModel)->forceFill(['id' => 1]);
$model2 = (new TestEloquentCollectionModel)->forceFill(['id' => 2]);

$c = new Collection;
$this->assertInstanceOf(Collection::class, $c->findOrFail([]));
$this->assertCount(0, $c->findOrFail([]));

$c->push($model1);
$this->assertCount(1, $c->findOrFail([1]));
$this->assertEquals(1, $c->findOrFail([1])->first()->id);

$c->push($model2);
$this->assertCount(2, $c->findOrFail([1, 2]));

$this->expectException(ModelNotFoundException::class);
$this->expectExceptionMessage('No query results for model [Illuminate\Tests\Database\TestEloquentCollectionModel] 3');

$c->findOrFail([1, 2, 3]);
}

public function testFindOrFailThrowsExceptionWithMessageWhenOtherModelsArePresent()
{
$model = (new TestEloquentCollectionModel)->forceFill(['id' => 1]);

$c = new Collection([$model]);

$this->expectException(ModelNotFoundException::class);
$this->expectExceptionMessage('No query results for model [Illuminate\Tests\Database\TestEloquentCollectionModel] 2');

$c->findOrFail(2);
}

public function testFindOrFailThrowsExceptionWithoutMessageWhenOtherModelsAreNotPresent()
{
$c = new Collection();

$this->expectException(ModelNotFoundException::class);
$this->expectExceptionMessage('');

$c->findOrFail(1);
}

public function testLoadMethodEagerLoadsGivenRelationships()
{
$c = $this->getMockBuilder(Collection::class)->onlyMethods(['first'])->setConstructorArgs([['foo']])->getMock();
Expand Down