Skip to content

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