Skip to content

Commit 699abd0

Browse files
authored
Consistent BelongsToMany#firstOrCreate behaviour (#37337)
1 parent e0ae5fc commit 699abd0

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -609,14 +609,15 @@ public function firstOrNew(array $attributes)
609609
* Get the first related record matching the attributes or create it.
610610
*
611611
* @param array $attributes
612+
* @param array $values
612613
* @param array $joining
613614
* @param bool $touch
614615
* @return \Illuminate\Database\Eloquent\Model
615616
*/
616-
public function firstOrCreate(array $attributes, array $joining = [], $touch = true)
617+
public function firstOrCreate(array $attributes, array $values = [], array $joining = [], $touch = true)
617618
{
618619
if (is_null($instance = $this->related->where($attributes)->first())) {
619-
$instance = $this->create($attributes, $joining, $touch);
620+
$instance = $this->create($attributes + $values, $joining, $touch);
620621
}
621622

622623
return $instance;

tests/Integration/Database/EloquentBelongsToManyTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -439,6 +439,30 @@ public function testFirstOrCreateMethod()
439439
$this->assertNotNull($new->id);
440440
}
441441

442+
public function testFirstOrCreateMethodWithValues()
443+
{
444+
$post = Post::create(['title' => Str::random()]);
445+
$tag = Tag::create(['name' => Str::random()]);
446+
$post->tags()->attach(Tag::all());
447+
448+
$existing = $post->tags()->firstOrCreate(
449+
['name' => $tag->name],
450+
['type' => 'featured']
451+
);
452+
453+
$this->assertEquals($tag->id, $existing->id);
454+
$this->assertNotEquals('foo', $existing->name);
455+
456+
$new = $post->tags()->firstOrCreate(
457+
['name' => 'foo'],
458+
['type' => 'featured']
459+
);
460+
461+
$this->assertSame('foo', $new->name);
462+
$this->assertSame('featured', $new->type);
463+
$this->assertNotNull($new->id);
464+
}
465+
442466
public function testUpdateOrCreateMethod()
443467
{
444468
$post = Post::create(['title' => Str::random()]);

0 commit comments

Comments
 (0)