We’ve all been there: trying updating a counter variable, then saving the entire model instance. It works, sure, but it feels…clunky, right? Especially when Laravel offers a more elegant solution: Eloquent’s increment
and decrement
methods!
In this post, we’ll explore how to ditch the manual update dance and embrace these time-saving methods for incrementing or decrementing values in your Laravel applications.
If you are trying to generate displayable username from the email then follow Easily Generate Displayable Username From Email in Laravel 2024
Why Eloquent’s Increment OR Decrement?
Let’s face it, manually updating a value, saving the model, and handling potential errors can get tedious. Eloquent’s increment
and decrement
methods streamline this process by offering a concise and efficient way to modify specific columns directly within the database.
Manual Update:
$article = Article::find($article_id);
$article->read_count++; // Manually increment read_count
$article->save();
Using increment
:
$article = Article::find($article_id);
$article->increment('read_count');
See the difference? The increment
method keeps things clean and concise.
Here’s how these methods work:
increment($column, $amount = 1)
: This method increases the value of a specified column in the database. The$column
argument represents the column name you want to modify, and the optional$amount
argument defines the increment value (defaults to 1).decrement($column, $amount = 1)
: Similar toincrement
, this method decreases the value of a column. Again, specify the column name with$column
and the decrement amount with the optional$amount
argument (defaults to 1).
Taking it a Step Further
Specifying the Increment/Decrement Amount: Remember the optional $amount
argument? You can use it to define the specific value to increment or decrement by. For example:
$article->increment('read_count', 10); // Increase read_count by 10
Using both increment and decrement in a model:
$article = Article::find($article_id);
$article->increment('read_count');
$article->decrement('stock');
Conclusion
By embracing Eloquent’s increment
and decrement
methods, you can streamline your code, improve readability, and save yourself valuable time.