Skip to content

Commit

Permalink
Add updateOrCreate method
Browse files Browse the repository at this point in the history
  • Loading branch information
stevebauman committed Sep 24, 2024
1 parent c977d3e commit 789c2ac
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,20 @@ public function firstOrCreate(array $attributes = [], array $values = []): Model
return $this->create($attributes + $values);
}

/**
* Update a model or create a new one.
*/
public function updateOrCreate(array $attributes, array $values = []): Model
{
if (! is_null($instance = (clone $this)->where($attributes)->first())) {
$instance->fill($values)->save();

return $instance;
}

return $this->create($attributes + $values);
}

/**
* Add a where clause to the query.
*/
Expand Down
18 changes: 18 additions & 0 deletions tests/ModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,24 @@
expect($found->wasRecentlyCreated)->toBeFalse();
});

it('can be updated or created with id', function () {
$model = ModelStub::updateOrCreate([
'id' => 'foo-bar',
], [
'name' => 'John Doe',
]);

$found = ModelStub::updateOrCreate([
'id' => 'foo-bar',
], [
'name' => 'Jane Doe',
]);

expect($model->is($found))->toBeTrue();
expect($model->name)->toBe('John Doe');
expect($found->name)->toBe('Jane Doe');
});

it('throws exception when creating a model with an empty key', function (mixed $id) {
ModelStub::create(['id' => $id]);
})->with([
Expand Down

0 comments on commit 789c2ac

Please sign in to comment.