I know i can reduce the column value in laravel using this query
DB::table('users')->decrement('votes', 5);
But i want to restrict the value from being become negative value.
Is there anyway to do this with laravel?
You'll need to use raw queries for that.
The following code should do the trick for all DB engines that support GREATEST function:
DB::table('users')->update(['votes' => DB::raw('GREATEST(votes - 5, 0)')]);
It will decrement votes column in users table by 5, but won't go below zero - that's what GREATEST function is used for.
If you really want to use decrement in this case (could be handy if you're accessing it through a relationship for example), you could do something like:
$thing->decrement('votes', $thing->votes - $amount <= 0 ? $thing->votes : $amount);
Where $amount
is 5 in your case. It's pretty ugly in my opinion. Worth noting if you already have $thing (say via a relationship) it won't trigger an additional query when accessing votes.
If you are only incrementing by 1, a simply if
wrapped around is cleaner:
if($thing->votes > 0) {
$thing->decrement('votes');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With