Home > Enterprise >  How to update with function in laravel query builder
How to update with function in laravel query builder

Time:02-13

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

CodePudding user response:

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.

CodePudding user response:

Updating Model in single line with its own property is not possible. All you can do is :

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