0

I'm doing a query and want to update the data, but I want to do a math operation first. How to simplify it?

my code below:

$jumlah = 10;
$Rpodetail = Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->first();
$total = $Rpodetail->sisa - $jumlah;
Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->update([
'sisa' => $total,
]);
                        
alexistdev
  • 57
  • 12

2 Answers2

0

you don't need to do another query for updating, simply:

$Rpodetail->update(['sisa' => $total]);

you can also use this answer for direct access to column values.

PJB
  • 46
  • 3
0
$jumlah = 10;
$Rpodetail = Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->first();
$total = $Rpodetail->sisa - $jumlah;
$Rpodetail->update([
    'sisa' => $total,
]);

Or

$jumlah = 10;
$Rpodetail = Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->first();
$Rpodetail->update([
    'sisa' => $Rpodetail->sisa - $jumlah,
]);

Or 1 line answer (According to @PBJ answer) with DB:raw() :

jumlah = 10;
Rpodetail::where('rpo_id',$request->postore)->where('produk_id',$produkid)->update(['
sisa' => DB::raw("sisa + '$jumlah'")]);
Aleksandar Đokić
  • 2,118
  • 17
  • 35