Skip to content

Commit

Permalink
Make the updateOrCreate methods in relations use firstOrCreate be…
Browse files Browse the repository at this point in the history
…hind the scenes

Related to laravel#48160, laravel#48192
  • Loading branch information
mpyw committed Aug 28, 2023
1 parent 4c5d4d5 commit 4b35f74
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 18 deletions.
14 changes: 5 additions & 9 deletions src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -672,17 +672,13 @@ public function createOrFirst(array $attributes = [], array $values = [], array
*/
public function updateOrCreate(array $attributes, array $values = [], array $joining = [], $touch = true)
{
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 {
$this->attach($instance, $joining, $touch);
}
}
$instance = $this->firstOrCreate($attributes, $values, $joining, $touch);

$instance->fill($values);
if (! $instance->wasRecentlyCreated) {
$instance->fill($values);

$instance->save(['touch' => false]);
$instance->save(['touch' => false]);
}

return $instance;
}
Expand Down
10 changes: 5 additions & 5 deletions src/Illuminate/Database/Eloquent/Relations/HasManyThrough.php
Original file line number Diff line number Diff line change
Expand Up @@ -271,11 +271,11 @@ public function firstOrNew(array $attributes)
*/
public function updateOrCreate(array $attributes, array $values = [])
{
$instance = $this->firstOrNew($attributes);

$instance->fill($values)->save();

return $instance;
return tap($this->firstOrCreate($attributes, $values), function ($instance) use ($values) {
if (! $instance->wasRecentlyCreated) {
$instance->fill($values)->save();
}
});
}

/**
Expand Down
8 changes: 4 additions & 4 deletions src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -267,10 +267,10 @@ public function createOrFirst(array $attributes = [], array $values = [])
*/
public function updateOrCreate(array $attributes, array $values = [])
{
return tap($this->firstOrNew($attributes), function ($instance) use ($values) {
$instance->fill($values);

$instance->save();
return tap($this->firstOrCreate($attributes, $values), function ($instance) use ($values) {
if (! $instance->wasRecentlyCreated) {
$instance->fill($values)->save();
}
});
}

Expand Down

0 comments on commit 4b35f74

Please sign in to comment.