Skip to content

Commit

Permalink
Merge pull request #29362 from mpyw/fix-update-existing-pivot-error-o…
Browse files Browse the repository at this point in the history
…n-non-existent-record

[5.8] Make updateExistingPivot() safe on non-existent pivot
  • Loading branch information
taylorotwell authored Aug 1, 2019
2 parents c7eaba6 + 5d87070 commit cc1b8f9
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -220,12 +220,12 @@ public function updateExistingPivot($id, array $attributes, $touch = true)
*/
protected function updateExistingPivotUsingCustomClass($id, array $attributes, $touch)
{
$updated = $this->getCurrentlyAttachedPivots()
$pivot = $this->getCurrentlyAttachedPivots()
->where($this->foreignPivotKey, $this->parent->{$this->parentKey})
->where($this->relatedPivotKey, $this->parseId($id))
->first()
->fill($attributes)
->isDirty();
->first();

$updated = $pivot ? $pivot->fill($attributes)->isDirty() : false;

$this->newPivot([
$this->foreignPivotKey => $this->parent->{$this->parentKey},
Expand Down
35 changes: 35 additions & 0 deletions tests/Integration/Database/EloquentBelongsToManyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,33 @@ public function test_custom_pivot_class_using_sync()
$this->assertNotEmpty($results['detached']);
}

public function test_custom_pivot_class_using_update_existing_pivot()
{
Carbon::setTestNow('2017-10-10 10:10:10');

$post = Post::create(['title' => Str::random()]);
$tag = TagWithCustomPivot::create(['name' => Str::random()]);

DB::table('posts_tags')->insert([
['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'empty'],
]);

// Test on actually existing pivot
$this->assertEquals(
1,
$post->tagsWithCustomExtraPivot()->updateExistingPivot($tag->id, ['flag' => 'exclude'])
);
foreach ($post->tagsWithCustomExtraPivot as $tag) {
$this->assertEquals('exclude', $tag->pivot->flag);
}

// Test on non-existent pivot
$this->assertEquals(
0,
$post->tagsWithCustomExtraPivot()->updateExistingPivot(0, ['flag' => 'exclude'])
);
}

public function test_attach_method()
{
$post = Post::create(['title' => Str::random()]);
Expand Down Expand Up @@ -776,6 +803,14 @@ public function tagsWithCustomPivot()
->withTimestamps();
}

public function tagsWithCustomExtraPivot()
{
return $this->belongsToMany(TagWithCustomPivot::class, 'posts_tags', 'post_id', 'tag_id')
->using(PostTagPivot::class)
->withTimestamps()
->withPivot('flag');
}

public function tagsWithCustomPivotClass()
{
return $this->belongsToMany(TagWithCustomPivot::class, PostTagPivot::class, 'post_id', 'tag_id');
Expand Down

0 comments on commit cc1b8f9

Please sign in to comment.