diff --git a/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php b/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php index 079bdd8b3bde..eeacad1d7dfe 100644 --- a/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php +++ b/src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php @@ -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; diff --git a/tests/Integration/Database/EloquentHasManyThroughTest.php b/tests/Integration/Database/EloquentHasManyThroughTest.php index 0f5c38508fb0..f377f745bcbc 100644 --- a/tests/Integration/Database/EloquentHasManyThroughTest.php +++ b/tests/Integration/Database/EloquentHasManyThroughTest.php @@ -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']);