Laravel 5.4: Directly Subtract number from column in database
Solution 1
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.
Solution 2
You can do it with raw query like,
User::where('username', $username)
->update(array(
'credit' => DB::raw('credit - 100')
));
I hope you will understand.
Related videos on Youtube
Amit Gupta
Hello and thanks for checking my profile. I have always been fond of developing websites since my childhood. I first developed a website for my college in my training session and then for myself. I made hundreds of websites but it all started in the year 2008 when I launched my first website GogruMogru.com that becomes really famous at that time when Facebook was just launched and not famous. After that, I have started working with IT Companies and delivered many websites for popular brands like Madame, Lakshita, Monte Carlo, BUVogue, Trident, Rockit etc. in CakePHP and Laravel with too much complexity. Not only in websites, but I also started playing with Apps. I have developed some of the Apps in Ionic and Android but my main focus is on developing E-commerce websites in Laravel. I always believe that you can achieve anything if you are desperate and focused.
Updated on June 04, 2022Comments
-
Amit Gupta almost 2 years
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.
-
Amit Gupta over 6 yearsThanks! I am trying this in my code and will let you know shortly if it works.
-
Amit Gupta over 6 yearsYour alternative is also correct but I found decrement built-in function of laravel better.
-
Sagar Gautam over 6 years@AmitGupta Yes this is one solution but solution provided above is better and you can make variable amount of decrement/increment with above solution
-
Joel Hinz over 6 yearsI'm glad it helped. :)