Home > Blockchain >  Laravel 8: Update a record in database using if statement
Laravel 8: Update a record in database using if statement

Time:06-18

Below is the function I used to update my record.

    public function store_upd_nilai_uji_program(Request $request)
    {
        $validated = $request->validate([
            'nip'       => 'required|numeric|digits_between:18,18',
            'n1'        => 'nullable|numeric',
            'n2'        => 'nullable|numeric',
            'n3'        => 'nullable|numeric',
            'n4'        => 'nullable|numeric',
            'n5'        => 'nullable|numeric',
            'n6'        => 'required|numeric',
            'tanggal'   => 'required',
            'waktu'     => 'required',
        ]);

        NilaiUjiProgram::where('nim', $request->nim)->update([
            'nip'                             => $request->nip,
            'nilai_kemampuan_dasar_program'   => floatval($request->n1),
            'nilai_kecocokan_algoritma'       => floatval($request->n2),
            'nilai_penguasaan_program'        => floatval($request->n3),
            'nilai_penguasaan_ui'             => floatval($request->n4),
            'nilai_validasi_output'           => floatval($request->n5),
            'total'                           => floatval($request->n6),
            'tanggal'                         => $request->tanggal,
            'waktu'                           => $request->waktu,
        ]);

        return redirect('/prodi/daftar_nilai_uji_program')->with('status', 'Nilai berhasil diperbaharui!');
    }

Actually, I want to update the attribute 'nilai_kemampuan_dasar_program', 'nilai_kecocokan_algoritma','nilai_penguasaan_program','nilai_penguasaan_ui', and 'nilai_validasi_output' if only the equal value in $request is NOT NULL. If the value is null, I would like to keep my record fill with NULL. To keep in mind that my table doesn't have any primary key. Do you have any idea how to solve my problem?

CodePudding user response:

 NilaiUjiProgram::where('nim', $request->nim)->update([
            'nip'                             => $request->nip,
            'nilai_kemampuan_dasar_program'   => $request->n1 ? floatval($request->n1) : null,
            'nilai_kecocokan_algoritma'       => $request->n2? floatval($request->n2) :null,
            'nilai_penguasaan_program'        => $request->n3 ? floatval($request->n3):null,
            'nilai_penguasaan_ui'             => $request->n4 ? floatval($request->n4) : null,
            'nilai_validasi_output'           => floatval($request->n5),
            'total'                           => floatval($request->n6),
            'tanggal'                         => $request->tanggal,
            'waktu'                           => $request->waktu,
        ]);
  • Related