2

i want update this data but unit id, rute asal and rute tujuan cant be duplicate.. in my case, i only want update biaya pengantaran but getting message data is duplicate (even though it's the data itself). can u solve my problem? sorry for my broken english

  public function update(Request $request, $id)
{
    $request->validate(
        [
            'unit_id' => 'required',
            'rute_asal' => 'required|regex:/^[\pL\s\-]+$/u',
            'rute_tujuan' => 'required|regex:/^[\pL\s\-]+$/u',
            'biaya_pengantaran' => 'required|numeric',
        ],
        [
            'unit_id.required' => 'Unit tidak boleh kosong!',
            'rute_asal.required' => 'Rute asal tidak boleh kosong!',
            'rute_tujuan.required' => 'Rute tujuan tidak boleh kosong!',
            'biaya_pengantaran.required' => 'Biaya pengantaran tidak boleh kosong!',
            'rute_asal.regex' => 'Rute asal tidak valid!',
            'rute_tujuan.regex' => 'Rute tujuan tidak valid!',
            'biaya_pengantaran.numeric' => 'Biaya pengantaran harus berupa angka!'
        ]
    );

    $unit = $request->unit_id;
    $asal = $request->rute_asal;
    $tujuan = $request->rute_tujuan;
    $cek = BiayaPengantaran::where(['unit_id' => $unit, 'rute_asal' => $asal, 'rute_tujuan' =>  $tujuan])->first();

    $biaya = BiayaPengantaran::find($id);

    if (!$cek) {
        $biaya->update([
            'unit_id' => $request->unit_id,
            'rute_asal' => $request->rute_asal,
            'rute_tujuan' => $request->rute_tujuan,
            'biaya_pengantaran' => $request->biaya_pengantaran,
        ]);
        return redirect('/biaya_pengantaran')->with([
            'message' => 'Data berhasil diperbarui',
            'success' => true
        ]);
    } else {
        throw ValidationException::withMessages([
            'unit_id' => 'Biaya pengantaran untuk unit dan rute pengantaran ini sudah diinputkan!',
            'rute_asal' => 'Rute asal untuk unit dan rute pengantaran ini sudah diinputkan!',
            'rute_tujuan' => 'Rute tujuan untuk unit dan rute pengantaran ini sudah diinputkan!'
        ]);
    }
}
2
  • You likely want to use the unique validation rule. Commented Jul 2, 2022 at 9:01
  • @Peppermintology case closed bro. thank you for ur respond Commented Jul 2, 2022 at 9:15

1 Answer 1

1

Make an exception in your check to the current ID

 $cek = BiayaPengantaran::where(['unit_id' => $unit, 'rute_asal' => $asal, 'rute_tujuan' =>  $tujuan])
    ->where('id', '!=', $id)
    ->first();
Sign up to request clarification or add additional context in comments.

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.