Skip to content

Commit 3e25680

Browse files
author
Ionut Rusen
committed
Add updateOrCreate and updateOrCreateWithoutRefresh methods
Introduced two new methods in `Eloquent\Builder` to streamline updating or creating model instances. `updateOrCreate` handles instance updates or creation with refresh, while `updateOrCreateWithoutRefresh` performs the same without triggering a refresh. These enhancements improve flexibility and control over model persistence.
1 parent ca05aab commit 3e25680

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/Eloquent/Builder.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,39 @@ public function updateWithoutRefresh(array $attributes = []): int
146146

147147
return $query->update($this->addUpdatedAtColumn($attributes));
148148
}
149+
public function updateOrCreate(array $attributes, array $values = []): Model
150+
{
151+
// Attempt to find an existing instance matching the attributes
152+
$instance = $this->firstWhere($attributes);
153+
154+
if ($instance) {
155+
// Update the instance if found
156+
$instance->fill($values)->save();
157+
} else {
158+
// Create a new instance with attributes and values merged
159+
$instance = $this->create(array_merge($attributes, $values));
160+
}
161+
162+
return $instance;
163+
}
164+
public function updateOrCreateWithoutRefresh(array $attributes, array $values = []): Model
165+
{
166+
// Attempt to find an existing instance matching the attributes
167+
$instance = $this->firstWhere($attributes);
168+
169+
if ($instance) {
170+
// Update the instance without triggering refresh
171+
$this->whereKey($instance->getKey())->updateWithoutRefresh($values);
172+
173+
// Refresh the instance in memory with updated values
174+
$instance->fill($values);
175+
} else {
176+
// Create a new instance without triggering a refresh
177+
$instance = $this->createWithoutRefresh(array_merge($attributes, $values));
178+
}
179+
180+
return $instance;
181+
}
149182

150183
public function firstOrCreateWithoutRefresh(array $attributes = [], array $values = [])
151184
{

0 commit comments

Comments
 (0)