3

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.

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hello Dilip, I think you posted your answer while I was writing mine. I think you are right :)
I apologies. I appreciated your answer is a detailed one. :)
2

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();

Comments

1

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

Comments

0

Pass update data as array

Try this way

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.