From 81da81283d45b1782a2444ff0931280c76c331ed Mon Sep 17 00:00:00 2001 From: Jason Daly Date: Wed, 18 May 2022 20:42:54 -0400 Subject: [PATCH] fix clone issue on updateOrCreate and firstOrCreate --- .../Eloquent/Relations/BelongsToMany.php | 4 +-- .../Database/EloquentBelongsToManyTest.php | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php index 5807f83fa690..d46b70c8cb24 100755 --- a/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php +++ b/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php @@ -618,7 +618,7 @@ public function firstOrNew(array $attributes = [], array $values = []) */ public function firstOrCreate(array $attributes = [], array $values = [], array $joining = [], $touch = true) { - if (is_null($instance = $this->clone()->where($attributes)->first())) { + if (is_null($instance = (clone $this)->where($attributes)->first())) { if (is_null($instance = $this->related->where($attributes)->first())) { $instance = $this->create(array_merge($attributes, $values), $joining, $touch); } else { @@ -640,7 +640,7 @@ public function firstOrCreate(array $attributes = [], array $values = [], array */ public function updateOrCreate(array $attributes, array $values = [], array $joining = [], $touch = true) { - if (is_null($instance = $this->clone()->where($attributes)->first())) { + if (is_null($instance = (clone $this)->where($attributes)->first())) { if (is_null($instance = $this->related->where($attributes)->first())) { return $this->create(array_merge($attributes, $values), $joining, $touch); } else { diff --git a/tests/Integration/Database/EloquentBelongsToManyTest.php b/tests/Integration/Database/EloquentBelongsToManyTest.php index 4ee8fd85d66e..ff95a4cdf02f 100644 --- a/tests/Integration/Database/EloquentBelongsToManyTest.php +++ b/tests/Integration/Database/EloquentBelongsToManyTest.php @@ -1154,6 +1154,42 @@ public function testFirstOrMethod() })->id ); } + + public function testUpdateOrCreateQueryBuilderIsolation() + { + $user = User::create(['name' => Str::random()]); + $post = Post::create(['title' => Str::random()]); + + $user->postsWithCustomPivot()->attach($post); + + $instance = $user->postsWithCustomPivot()->updateOrCreate( + ['uuid' => $post->uuid], + ['title' => Str::random()], + ); + + $this->assertArrayNotHasKey( + 'user_uuid', + $instance->toArray(), + ); + } + + public function testFirstOrCreateQueryBuilderIsolation() + { + $user = User::create(['name' => Str::random()]); + $post = Post::create(['title' => Str::random()]); + + $user->postsWithCustomPivot()->attach($post); + + $instance = $user->postsWithCustomPivot()->firstOrCreate( + ['uuid' => $post->uuid], + ['title' => Str::random()], + ); + + $this->assertArrayNotHasKey( + 'user_uuid', + $instance->toArray(), + ); + } } class User extends Model