How to increment or decrement in Laravel in one line

Categorized as Laravel Tagged

When dealing with product stock, you may need to update the current stock based on a delivery or sale. With Laravel, you can have some clean and tidy lines of code for that.

// ❌ You could do it like this
$product = Product::find($id);
// In case of delivery
$product->current_stock = $product->current_stock + 100;
// In case of sale
$product->current_stock = $product->current_stock - 1;
$product->save;

// ✅ You could do it like this but in one line
// for a delivery
$product = Product::find($id)->increment('current_stock', 100);
// for a sale
$product = Product::find($id)->decrement('current_stock', 2);

Leave a reply

Your email address will not be published. Required fields are marked *