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

[5.6] access to parent model from withDefault closure #23334

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
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ protected function getDefaultFor(Model $parent)
$instance = $this->newRelatedInstanceFor($parent);

if (is_callable($this->withDefault)) {
return call_user_func($this->withDefault, $instance) ?: $instance;
return call_user_func($this->withDefault, $instance, $parent) ?: $instance;
}

if (is_array($this->withDefault)) {
Expand Down
20 changes: 20 additions & 0 deletions tests/Database/DatabaseEloquentHasOneTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,25 @@ public function testHasOneWithDynamicDefault()
$this->assertSame(1, $newModel->getAttribute('foreign_key'));
}

public function testHasOneWithDynamicDefaultUseParentModel()
{
$relation = $this->getRelation()->withDefault(function ($newModel, $parentModel) {
$newModel->username = $parentModel->username;
});

$this->builder->shouldReceive('first')->once()->andReturnNull();

$newModel = new EloquentHasOneModelStub;

$this->related->shouldReceive('newInstance')->once()->andReturn($newModel);

$this->assertSame($newModel, $relation->getResults());

$this->assertSame('taylor', $newModel->username);

$this->assertSame(1, $newModel->getAttribute('foreign_key'));
}

public function testHasOneWithArrayDefault()
{
$attributes = ['username' => 'taylor'];
Expand Down Expand Up @@ -191,6 +210,7 @@ protected function getRelation()
$this->builder->shouldReceive('getModel')->andReturn($this->related);
$this->parent = m::mock('Illuminate\Database\Eloquent\Model');
$this->parent->shouldReceive('getAttribute')->with('id')->andReturn(1);
$this->parent->shouldReceive('getAttribute')->with('username')->andReturn('taylor');
$this->parent->shouldReceive('getCreatedAtColumn')->andReturn('created_at');
$this->parent->shouldReceive('getUpdatedAtColumn')->andReturn('updated_at');
$this->parent->shouldReceive('newQueryWithoutScopes')->andReturn($this->builder);
Expand Down