Skip to content

[11.x] Add IncrementOrCreate method to Eloquent#54300

Merged
taylorotwell merged 3 commits into
laravel:11.xfrom
carloeusebi:feat/increment-or-create
Jan 22, 2025
Merged

[11.x] Add IncrementOrCreate method to Eloquent#54300
taylorotwell merged 3 commits into
laravel:11.xfrom
carloeusebi:feat/increment-or-create

Conversation

@carloeusebi

@carloeusebi carloeusebi commented Jan 22, 2025

Copy link
Copy Markdown
Contributor

Laravel has methods like updateOrCreate, firstOrCreate and such. I think incrementOrCreate fits Eloquent, and to be fair I expected it existed already.

The use case:

Let's imagine we are tracking the exceptions in our application, but we don't want to add a new record every time the same exception occurred but we want to update the number of times the exception happened.

BackendException::incrementOrCreate(['name' => $name, 'file' => $file, 'line' => $line]);

This method will create a new model with ['count' => 1] the first time the exception happens, and increment the count attribute for the next occurencies.

The column name and the default increment value can also be customized.

BackendException::incrementOrCreate($attributes, 'occurrences', 0);

You can also pass increment() $step and $extra parameters.

BackendException::incrementOrCreate($attributes, step: 2, extra: ['trace' => $trace]);

@shaedrich

shaedrich commented Jan 22, 2025

Copy link
Copy Markdown
Contributor

You may want to add a $step argument, defaulting to 1, to specify by which the column should be incremented, mimicking the behavior of increment(), which it wraps. It furthermore offers to provide an array of columns to update alongside the increment operation.

@carloeusebi

Copy link
Copy Markdown
Contributor Author

@shaedrich thank you for your feedback, I didn't think of that.

@carloeusebi carloeusebi force-pushed the feat/increment-or-create branch from 856a8ad to 1f4f87c Compare January 22, 2025 11:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants