Skip to content
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
7 changes: 4 additions & 3 deletions src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down
38 changes: 38 additions & 0 deletions tests/Integration/Database/EloquentBelongsToManyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()]);
Expand All @@ -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()
Expand Down