diff --git a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php index db69f3390981..18fa14517bbf 100755 --- a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php @@ -594,12 +594,13 @@ public function findOrNew($id, $columns = ['*']) * 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->related->where($attributes)->first())) { - $instance = $this->related->newInstance($attributes); + $instance = $this->related->newInstance(array_merge($attributes, $values)); } return $instance; @@ -617,7 +618,7 @@ public function firstOrNew(array $attributes = []) public function firstOrCreate(array $attributes = [], array $values = [], array $joining = [], $touch = true) { if (is_null($instance = $this->related->where($attributes)->first())) { - $instance = $this->create($attributes + $values, $joining, $touch); + $instance = $this->create(array_merge($attributes, $values), $joining, $touch); } return $instance; diff --git a/tests/Integration/Database/EloquentBelongsToManyTest.php b/tests/Integration/Database/EloquentBelongsToManyTest.php index 61f33f5f8a38..e801b93e46b3 100644 --- a/tests/Integration/Database/EloquentBelongsToManyTest.php +++ b/tests/Integration/Database/EloquentBelongsToManyTest.php @@ -439,6 +439,36 @@ public function testFirstOrCreateMethod() $this->assertNotNull($new->id); } + public function testFirstOrNewMethodWithValues() + { + $post = Post::create(['title' => Str::random()]); + $tag = Tag::create(['name' => Str::random()]); + $post->tags()->attach(Tag::all()); + + $existing = $post->tags()->firstOrNew( + ['name' => $tag->name], + ['type' => 'featured'] + ); + + $this->assertEquals($tag->id, $existing->id); + $this->assertNotEquals('foo', $existing->name); + + $new = $post->tags()->firstOrNew( + ['name' => 'foo'], + ['type' => 'featured'] + ); + + $this->assertSame('foo', $new->name); + $this->assertSame('featured', $new->type); + + $new = $post->tags()->firstOrNew( + ['name' => 'foo'], + ['name' => 'bar'] + ); + + $this->assertSame('bar', $new->name); + } + public function testFirstOrCreateMethodWithValues() { $post = Post::create(['title' => Str::random()]); @@ -461,6 +491,14 @@ public function testFirstOrCreateMethodWithValues() $this->assertSame('foo', $new->name); $this->assertSame('featured', $new->type); $this->assertNotNull($new->id); + + $new = $post->tags()->firstOrCreate( + ['name' => 'qux'], + ['name' => 'bar'] + ); + + $this->assertSame('bar', $new->name); + $this->assertNotNull($new->id); } public function testUpdateOrCreateMethod()