diff --git a/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php b/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php index adc538f8c09b..5bdf1c08b5bd 100644 --- a/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php +++ b/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php @@ -188,7 +188,7 @@ public function updateExistingPivot($id, array $attributes, $touch = true) $attributes = $this->addTimestampsToAttachment($attributes, true); } - $updated = $this->newPivotStatementForId($id)->update( + $updated = $this->newPivotStatementForId($this->parseId($id))->update( $this->castAttributes($attributes) ); @@ -488,6 +488,21 @@ protected function parseIds($value) return (array) $value; } + /** + * Get the ID from the given mixed value. + * + * @param mixed $value + * @return mixed + */ + protected function parseId($value) + { + if ($value instanceof Model) { + return $value->getKey(); + } + + return $value; + } + /** * Cast the given keys to integers if they are numeric and string otherwise. * diff --git a/tests/Integration/Database/EloquentBelongsToManyTest.php b/tests/Integration/Database/EloquentBelongsToManyTest.php index 983637ab2f38..06a7b3fd0d53 100644 --- a/tests/Integration/Database/EloquentBelongsToManyTest.php +++ b/tests/Integration/Database/EloquentBelongsToManyTest.php @@ -584,6 +584,44 @@ public function can_touch_related_models() $this->assertNotEquals('2017-10-10 10:10:10', Tag::find(300)->updated_at); } + + /** + * @test + */ + public function can_update_existing_pivot() + { + $tag = Tag::create(['name' => str_random()]); + $post = Post::create(['title' => str_random()]); + + DB::table('posts_tags')->insert([ + ['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'empty'], + ]); + + $post->tagsWithExtraPivot()->updateExistingPivot($tag->id, ['flag' => 'exclude']); + + foreach ($post->tagsWithExtraPivot as $tag) { + $this->assertEquals('exclude', $tag->pivot->flag); + } + } + + /** + * @test + */ + public function can_update_existing_pivot_using_model() + { + $tag = Tag::create(['name' => str_random()]); + $post = Post::create(['title' => str_random()]); + + DB::table('posts_tags')->insert([ + ['post_id' => $post->id, 'tag_id' => $tag->id, 'flag' => 'empty'], + ]); + + $post->tagsWithExtraPivot()->updateExistingPivot($tag, ['flag' => 'exclude']); + + foreach ($post->tagsWithExtraPivot as $tag) { + $this->assertEquals('exclude', $tag->pivot->flag); + } + } } class Post extends Model @@ -601,6 +639,12 @@ public function tags() ->wherePivot('flag', '<>', 'exclude'); } + public function tagsWithExtraPivot() + { + return $this->belongsToMany(Tag::class, 'posts_tags', 'post_id', 'tag_id') + ->withPivot('flag'); + } + public function touchingTags() { return $this->belongsToMany(TouchingTag::class, 'posts_tags', 'post_id', 'tag_id')