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');"
$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]);
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.
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.
$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.
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
));
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')]);
This worked fine for me
\Models\User::where("id", $userId)->increment("points");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With