Skip to content

Commit

Permalink
Make the updateOrCreate methods in relations use firstOrCreate
Browse files Browse the repository at this point in the history
Related to #48160, #48192
  • Loading branch information
mpyw committed Aug 28, 2023
1 parent 4c5d4d5 commit 892c9ba
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 21 deletions.
18 changes: 6 additions & 12 deletions src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -672,19 +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->fill($values);
return tap($this->firstOrCreate($attributes, $values), function ($instance) use ($values) {
if (! $instance->wasRecentlyCreated) {
$instance->fill($values);

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

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

/**
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 892c9ba

Please sign in to comment.