Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel decrement column value but not negative

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?

like image 512
siddiq Avatar asked Dec 18 '22 12:12

siddiq


2 Answers

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.

like image 54
jedrzej.kurylo Avatar answered Dec 31 '22 03:12

jedrzej.kurylo


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');
        }
like image 44
Chris Avatar answered Dec 31 '22 04:12

Chris