Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 4: how to subtract one from current value of column when updating rows?

I was wondering how to perform something like this:

Table::update(array('position'=>'position+1'));

As far as I know, laravel 4 handles 'position+1' as a string, thus is becomes 0.

I want to perform something like

UPDATE table SET position = position + 1

Can I do that using eloquent?

EDIT: nevermind, doh.."DB::table('users')->increment('votes');"

like image 885
Meddie Avatar asked Oct 10 '13 22:10

Meddie


People also ask

How do you subtract in laravel?

$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]);

How to subtract two values in SQL in same table?

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.

Which method is used to update data in laravel?

We can update the records using the DB facade with update method. The syntax of update method is as shown in the following table. Run an update statement against the database.

How do I change the last row in laravel?

$lastUser = App\User::orderBy('created_at', 'desc')->first(); after you can update your model like this: $lastUser->name = "New Name"; $lastUser->save(); UPDATE: you can also use the id field instead of 'created_at' for ordering your data.


3 Answers

Simply make use of the increment method:

DB::table('users')->increment('position');

The same is valid for decrement:

DB::table('users')->decrement('rank');

You may even set the second parameter to the amount you want to add/subtract:

DB::table('users')->increment('posts', 5);
DB::table('users')->decrement('likes', 3);

Also, if you need to update other columns along with it, you pass it as the third parameter:

DB::table('users')->increment('range', 3, array(
    'name' => 'Raphael',
    'rank' => 10
));

And the same goes for Eloquent models, as well:

$firstUser = User::find(1);
$firstUser->increment('height', 0.1, array(
    'active' => false
));
like image 63
rmobis Avatar answered Sep 30 '22 09:09

rmobis


you can also do with DB::raw method like this:

DB::table('tablename')->where(your condition)->update(['position' => DB::raw('position+1')]);

you can also do other operations with this like

DB::table('tablename')->where(your condition)->update(['position' => DB::raw('position * 2')]);
like image 26
utsav Avatar answered Sep 30 '22 09:09

utsav


This worked fine for me

\Models\User::where("id", $userId)->increment("points");
like image 3
Sajjad Ashraf Avatar answered Sep 30 '22 10:09

Sajjad Ashraf