Sling Academy
Home/PHP/Increment and Decrement of Column Values in Laravel Query Builder

Increment and Decrement of Column Values in Laravel Query Builder

Last updated: January 17, 2024

Introduction

Laravel’s fluent query builder provides a convenient and easy-to-read way of interacting with databases. When you need to update a numeric column to increment or decrement its current value, Laravel provides simple methods to do so. In this tutorial, we will explore how to use these methods in your Laravel applications for efficient database updates.

Why Use Increment/Decrement Methods?

Let’s imagine you have an application that keeps track of stock levels in a store. Each time an item is sold, the stock quantity needs to be reduced by one. Instead of fetching the current stock level, decremnting it in PHP, and updating the record, Laravel allows you to do this with a single query. This is not only more concise and readable but also reduces the chance of a race condition if two sales happen at almost the same time.

Using Increment

$affectedRows = DB::table('products')
             ->where('id', 1)
             ->increment('stock', 1);
echo $affectedRows; // Outputs the number of affected rows

In the example above, we are incrementing the ‘stock’ column of the products table for a product with an id of 1. The second argument to the increment method is the amount by which the stock should be incremented. In this case, we’re increasing it by one.

Using Decrement

$affectedRows = DB::table('products')
             ->where('id', 1)
             ->decrement('stock', 1);
echo $affectedRows; // Outputs the number of affected rows

The decrement method works similarly to increment but decreases the value of the specified column. Here, we decrease the stock level by one.

Additional Conditions

You can chain other query constraints when using increment/decrement methods:

$affectedRows = DB::table('products')
             ->where('quantity', '>', 0)
             ->where('active', 1)
             ->decrement('quantity', 1);

Other query methods like orWhere, having, and so on, can also be used.

Using With Additional Columns

Sometimes, you might want to update other columns in the same row when incrementing or decrementing a value. Laravel allows for this with an additional array argument:

DB::table('products')
->where('id', 1)
->increment('stock', 1, [
    'last_updated' => now()
]);

In the code above, the ‘last_updated’ column will be set to the current timestamp when the ‘stock’ column is incremented.

Manually Using Update Queries

If you prefer not to use the increment or decrement helpers, or you need more complexity, you can manually construct an update statement to achieve the same result:

DB::table('products')
->where('id', 1)
->update([
    'stock' => DB::raw('stock + 1')
]);

This method uses the DB::raw() method to manually specify the raw SQL operation.

Eloquent Models

If you are working with Eloquent models, the process is equally as straightforward:

$product = Product::find(1);
$product->increment('stock');
// or
$product->decrement('stock');

Keep in mind that the increment and decrement methods on Eloquent models save the model immediately, so there is no need to call save() afterwards.

Transaction Safety

Whenever dealing with operations that change database records, you should consider using database transactions to ensure data integrity. Laravel provides a simple way to use transactions:

DB::transaction(function () {
    DB::table('products')->where('id', 1)->increment('stock');
});

If an exception is thrown inside the transaction Closure, Laravel will automatically roll back the transaction.

Conclusion

In summary, Laravel’s query builder provides a fluent interface to increment or decrement values in your database directly, while eloquent models also simplify this operation for active record manipulation. Remember to handle multi-user environments and potential race conditions with appropriate transaction use.

Whether you’re working on user profiles with points systems, e-commerce platforms managing inventory, or any other system that modifies numerical values, these techniques for incrementing and decrementing values can help you write concise and efficient database interactions. As always, make sure to consult the Laravel documentation for the latest best practices and updates in query building techniques.

Next Article: Deleting Records with Conditions in Laravel Query Builder

Previous Article: How to update JSON column in Laravel Query Builder

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array