Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 3 commits into from
Jan 22, 2025

Conversation

carloeusebi
Copy link
Contributor

@carloeusebi carloeusebi commented Jan 22, 2025

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
Copy link
Contributor

shaedrich commented Jan 22, 2025

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
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
@carloeusebi carloeusebi force-pushed the feat/increment-or-create branch from 1f4f87c to 8c1a28d Compare January 22, 2025 11:25
@taylorotwell taylorotwell merged commit b89006c into laravel:11.x Jan 22, 2025
38 checks passed
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