Skip to content

Commit

Permalink
Fix the firstOrNew method on HasManyThrough relations
Browse files Browse the repository at this point in the history
  • Loading branch information
tonysm committed Sep 26, 2023
1 parent ac91af7 commit 8492996
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php
Original file line number Diff line number Diff line change
Expand Up @@ -252,12 +252,13 @@ protected function buildDictionary(Collection $results)
* Get the first related model record matching the attributes or instantiate it.
*
* @param array $attributes
* @param array $values
* @return \Illuminate\Database\Eloquent\Model
*/
public function firstOrNew(array $attributes)
public function firstOrNew(array $attributes = [], array $values = [])
{
if (is_null($instance = $this->where($attributes)->first())) {
$instance = $this->related->newInstance($attributes);
$instance = $this->related->newInstance(array_merge($attributes, $values));
}

return $instance;
Expand Down
16 changes: 16 additions & 0 deletions tests/Integration/Database/EloquentHasManyThroughTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,22 @@ public function testHasSameParentAndThroughParentTable()
$this->assertEquals([1], $categories->pluck('id')->all());
}

public function testFirstOrNewOnMissingRecord()
{
$taylor = User::create(['name' => 'Taylor', 'slug' => 'taylor']);
$team = Team::create(['owner_id' => $taylor->id]);

$user1 = $taylor->teamMates()->firstOrNew(
['slug' => 'tony'],
['name' => 'Tony', 'team_id' => $team->id],
);

$this->assertFalse($user1->exists);
$this->assertEquals($team->id, $user1->team_id);
$this->assertSame('tony', $user1->slug);
$this->assertSame('Tony', $user1->name);
}

public function testFirstOrCreateWhenModelDoesntExist()
{
$owner = User::create(['name' => 'Taylor']);
Expand Down

0 comments on commit 8492996

Please sign in to comment.