Skip to content

Commit 82f31e0

Browse files
committed
[Dev] Added withoutEvents for firstOrCreate method
1 parent 5577816 commit 82f31e0

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

src/Contracts/RepositoryInterface.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public function firstWhere(array $where, $columns = ['*']): mixed;
2525

2626
public function firstOrNew(array $attributes, array $values = []): mixed;
2727

28-
public function firstOrCreate(array $attributes, array $values = []): mixed;
28+
public function firstOrCreate(array $attributes, array $values = [], bool $withoutEvents = false): mixed;
2929

3030
public function limit($limit, $columns = ['*']): mixed;
3131

src/Eloquent/BaseRepository.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -178,12 +178,18 @@ public function firstOrNew(array $attributes, array $values = []): mixed
178178
return $model;
179179
}
180180

181-
public function firstOrCreate(array $attributes, array $values = []): mixed
181+
public function firstOrCreate(array $attributes, array $values = [], bool $withoutEvents = false): mixed
182182
{
183183
$this->applyCriteria();
184184
$this->applyScope();
185185

186-
$model = $this->model->firstOrCreate($attributes, $values);
186+
if (!is_null($model = $this->model->where($attributes)->first())) {
187+
$this->resetModel();
188+
return $model;
189+
}
190+
191+
$method = $withoutEvents ? 'saveQuietly' : 'save';
192+
$model = tap($this->model->newModelInstance([...$attributes, ...$values]), fn ($instance) => $instance->{$method}());
187193
$this->resetModel();
188194

189195
event(new RepositoryEntityCreated($this, $model));

0 commit comments

Comments
 (0)