Laravel updateOrCreate make some condition

1.6k Views Asked by At

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;
}
1

There are 1 best solutions below

3
On

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 property exists on the resulting object. If it doesn't, we set the kode_rekening property and save it.

// Create or find the object
$kegiatan = UraianKegiatan::firstOrNew([
        'id' => $this->uraiankegiatanid
    ], [
        'uraian_id' => $this->newid, 
        'uraian' => $this->uraian ,
        'anggaran' => $anggaran ,
    ]);

// If the property does not exists, specify the kode_rekening attribute and save it
if (!$kegiatan->exists) {
    $kegiatan->kode_rekening = $kode.'.'.$new;
}

// If any values was changed, or the object was recently created, save it
if ($kegiatan->isDirty()) {
    $kegiatan->save(); 
}