Laravel 5.4: Directly Subtract number from column in database
Asked Answered
T

2

5

I want to subtract 100 number from credit column in database that is having int data type. I am looking for the way to directly subtract it with some Laravel query. But right now I first get the column value from the table and then subtract and then need to write update query to update it like below:

$subtractCredit = 100;

// Get Total Credit
$totalCredit = User::select('credit')->where(['username'=>$username])-
>first(); 

// Subtract 100 from Total Credit
$totalCredit = $totalCredit->credit - $subtractCredit;

// Update Credit in Table
User::where(['username'=>$username])->update(['credit' => $totalCredit]);

In the above code, I first get total credit from query and then subtract 100 from total credit and then update credit again with update query.

Please let me know the better approach of doing it.

Thrombus answered 22/11, 2017 at 10:14 Comment(0)
L
9

There's a built-in function to decrement:

User::where('username', $username)->decrement('credit', 100);

Docs: https://laravel.com/docs/5.4/queries#increment-and-decrement

Note that it's sugar for the update statement, so you don't need to call save() or update() afterwards.

Linger answered 22/11, 2017 at 10:23 Comment(1)
Thanks! I am trying this in my code and will let you know shortly if it works.Thrombus
T
5

You can do it with raw query like,

User::where('username', $username)
->update(array(
    'credit' => DB::raw('credit - 100')
));

I hope you will understand.

Tanka answered 22/11, 2017 at 10:20 Comment(2)
Your alternative is also correct but I found decrement built-in function of laravel better.Thrombus
@AmitGupta Yes this is one solution but solution provided above is better and you can make variable amount of decrement/increment with above solutionTanka

© 2022 - 2024 — McMap. All rights reserved.