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

[8.x] Adds the valueOfFail() Eloquent builder method #38707

Merged
merged 1 commit into from
Sep 8, 2021
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
13 changes: 13 additions & 0 deletions src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,19 @@ public function value($column)
}
}

/**
* Get a single column's value from the first result of the query or throw an exception.
*
* @param string|\Illuminate\Database\Query\Expression $column
* @return mixed
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
*/
public function valueOrFail($column)
{
return $this->firstOrFail([$column])->{Str::afterLast($column, '.')};
}

/**
* Execute the query as a "select" statement.
*
Expand Down
23 changes: 23 additions & 0 deletions tests/Database/DatabaseEloquentBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,29 @@ public function testValueMethodWithModelNotFound()
$this->assertNull($builder->value('name'));
}

public function testValueOrFailMethodWithModelFound()
{
$builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]);
$mockModel = new stdClass;
$mockModel->name = 'foo';
$builder->shouldReceive('first')->with(['name'])->andReturn($mockModel);

$this->assertSame('foo', $builder->valueOrFail('name'));
}

public function testValueOrFailMethodWithModelNotFoundThrowsModelNotFoundException()
{
$this->expectException(ModelNotFoundException::class);

$builder = m::mock(Builder::class.'[first]', [$this->getMockQueryBuilder()]);
$model = $this->getMockModel();
$model->shouldReceive('getKeyType')->once()->andReturn('int');
$builder->setModel($model);
$builder->getQuery()->shouldReceive('where')->once()->with('foo_table.foo', '=', 'bar');
$builder->shouldReceive('first')->with(['column'])->andReturn(null);
$builder->whereKey('bar')->valueOrFail('column');
}

public function testChunkWithLastChunkComplete()
{
$builder = m::mock(Builder::class.'[forPage,get]', [$this->getMockQueryBuilder()]);
Expand Down