I have function using laravel livewire using updateOrCreate , but i have function to looping number and its make update have wrong value . so what how to know this input this is update or this is create ? and how to manipulate this with if else ? like if its create .... , or elseif update ....
its my function
public function store_uraian()
{
$data = $this->anggaran ;
$kode = $this->k_koderek ;
$anggaran = str_replace(".", "", $data);
$first = UraianKegiatan::all()->count();
if ($first < 9) {
$new = sprintf("0%d", $first + 1);
} else {
$new = $first + 1;
}
UraianKegiatan::updateOrCreate(['id' => $this->uraiankegiatanid],[
'uraian_id' => $this->newid,
'kode_rekening' => $kode.'.'.$new, // on here i have problem
'uraian' => $this->uraian ,
'anggaran' => $anggaran ,
]);
$this->hideModal();
$this->emit('alert', ['type' => 'success', 'message' =>'Succes Melakukan Input / Update']);
}
My problem is on the line 'kode_rekening' => $kode.'.'.$new, // on here i have problem
If i do create function its normal and working, but if update its make wrong value. How to detect this is creating or this is updating the row? And how make condition like
if (create) {
'kode_rekening' => $kode.'.'.$new,
} else {
'kode_rekening' => $this->kode_rekening;
}
You can't know if the value is being updated or inserted when you use
updateOrCreate()
and pass the value you want to conditionally set. You need to attempt to fetch the actual instance first, then you can check if it exists or not.Instead we will use
firstOrNew()
, and check the propertyexists
on the resulting object. If it doesn't, we set thekode_rekening
property and save it.