diff --git a/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php b/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php index f589dd681c5a..70cf998aae3d 100644 --- a/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php +++ b/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php @@ -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}, diff --git a/tests/Integration/Database/EloquentBelongsToManyTest.php b/tests/Integration/Database/EloquentBelongsToManyTest.php index 3e87dea09fed..f74f33fc0d69 100644 --- a/tests/Integration/Database/EloquentBelongsToManyTest.php +++ b/tests/Integration/Database/EloquentBelongsToManyTest.php @@ -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()]); @@ -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');