Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4: Directly Subtract number from column in database

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.

like image 442
Amit Gupta Avatar asked Nov 22 '17 10:11

Amit Gupta


People also ask

How do you subtract in laravel?

You can subtract days on current date using carbon in laravel 6, laravel 7 and laravel 8 version. If you need to subtract day or more days in date then you can use carbon in laravel. carbon provide subDay() and subDays() method to add days on carbon date object.

How do you subtract a value in SQL?

The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query.

How do I subtract two records in SQL?

The SQL MINUS operator is used to return all rows in the first SELECT statement that are not returned by the second SELECT statement. Each SELECT statement will define a dataset. The MINUS operator will retrieve all records from the first dataset and then remove from the results all records from the second dataset.


2 Answers

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.

like image 127
Joel Hinz Avatar answered Oct 12 '22 23:10

Joel Hinz


You can do it with raw query like,

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

I hope you will understand.

like image 37
Sagar Gautam Avatar answered Oct 13 '22 01:10

Sagar Gautam