Skip to content

Commit

Permalink
Adds the valueOfFail(). (#38707)
Browse files Browse the repository at this point in the history
  • Loading branch information
DarkGhostHunter authored Sep 8, 2021
1 parent 408dc67 commit d73de59
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
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

0 comments on commit d73de59

Please sign in to comment.