Skip to content

Conversation

@sediqzada94
Copy link

Add decrementOrCreate Method to Laravel Eloquent Models

This pull request introduces a new method decrementOrCreate to Laravel's Eloquent Builder. This addition follows the recently merged pull request (#54300) that added the incrementOrCreate method. The decrementOrCreate method provide a straightforward approach to either decrement an existing model's column or create a new model if no existing model matches the provided attributes.

Purpose

The decrementOrCreate method is particularly useful for applications that require decrement operations within their logic, such as inventory management systems where stock levels need to be adjusted down automatically.

Usage Example

The following example demonstrates how to use the decrementOrCreate method in a product inventory scenario:

$product = Product::decrementOrCreate(
    ['name' => 'Laptop'],
    column: 'quantity',
    step: 2,
    extra: [],
);

@shaedrich
Copy link
Contributor

Should there be a check and an exception for when an unsigned column will go below 0 with the attempted decrement?

@taylorotwell
Copy link
Member

This is a much less common use case.

@sediqzada94
Copy link
Author

Should there be a check and an exception for when an unsigned column will go below 0 with the attempted decrement?

That is logical, but the PR is already closed.

@sediqzada94 sediqzada94 deleted the feat/decrement-or-create branch April 21, 2025 09:46
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