Gunaseelan
Gunaseelan

Reputation: 2542

Laravel update query (Add a value to existing a value)

I am trying to update a record using Laravel.

I have gone through lot of StackOverflow Questions to check whether this question is already raised.

mysql query : UPDATE students SET total_marks = total_marks + 80 WHERE id = 1

I have to translate this mysql query into Laravel query builder, but couldn't get a solution yet.

Instead of getting the early value from DB before update, Can we update the table with one update query using Laravel Query Builder.

2 Queries way:

$student_marks = Students::select('total_marks')->where('id','=',1);
$current_mark = $student_marks['total_marks']+80;

$update_student_marks = Students::where('id','=',1)->update('total_marks','=',$current_mark);

How to update a record like this with single query builder in Laravel.

Upvotes: 3

Views: 4625

Answers (4)

AExplosion
AExplosion

Reputation: 81

Here is how I approach this. For example, updating a wallet balance. Since the database server is different, the user could log into multiple devices and use the time between updating and saving to their advantage. So instead, I just do it on the database server since it is able to handle transactions, the user will have a negative balance when overuse occurs.

DB::update(DB::raw("UPDATE wallets set balance = balance - ? where id = ?"), [$amount, $this->id]);

Upvotes: 1

Guilherme Assemany
Guilherme Assemany

Reputation: 686

I think you need to make a few adjustments to your query.

First, you need to select the student correctly and than use Eloquent to call save method on it after setting the property to the correct value. I assume you are on Laravel 6.

$student_marks = Students::find($id);
$student_marks->total_marks += 80;
$student_marks->save();

Please, take a look at Laravel docs:

https://laravel.com/docs/6.x/eloquent

The reading takes some time but its definitely worth it. You will learn how to deal with eloquent and make your code better by using the most appropriate techniques.

Upvotes: 4

Burnie
Burnie

Reputation: 27

You can use the save function for this.

$student_marks = Students::select('total_marks')->where('id','=',1);
$student_marks->total_marks += 80; //or $student_marks->total_marks = $student_marks->total_marks + 80;
$student_marks->save();

Upvotes: 2

Bhargav Chudasama
Bhargav Chudasama

Reputation: 7161

Pass update data as array

Try this way

$update = array('total_marks'=>$current_mark);
$update_student_marks = Students::where('id','=',1)->update($update);

Upvotes: 0

Related Questions