Home > OS >  Update on IF ELSE Condition [Laravel]
Update on IF ELSE Condition [Laravel]

Time:01-17

I'm trying to find a way how to update 'Staff' table with column name 'kelompok_umur_id' set to 0 on update.

The use case is, on update the selected dropdown is showing who is the current tutor on the current class. But what I want to achieve is how to update the current selected tutor on the column name 'kelompok_umur_id' is set to 0 if the dropdown get selected to others entry (which is other tutor). So the condition here is only one tutor can teach one class.

https://imgur.com/a/do7YdIb

On my current state, it's updating the current selected tutor who previously has 0 value on 'kelompok_umur_id' with the selected class, but the previous selected tutor still has previous 'kelompok_umur_id' value.

Here's my current controller

$request->all();

        $validatedData =KelompokUmur::find($id);

        $validatedData->update([
            'ku_name'        => $request->ku_name,
            'ku_description' => $request->ku_description,
        ]);

        $staff = StaffPPA::where('kelompok_umur_id', 0)->first();
        if($staff){
            $staff->update([
                'kelompok_umur_id' => $id
            ]);
        } elseif ($staff->where('kelompok_umur_id', '!=', $staff->id->first())) {
            $staff->update([
                'kelompok_umur_id' => 0
            ]);
        } else {
            $staff->update([
                'kelompok_umur_id' => 0
            ]);
        }

If my questions still unclear, lemme know! Any help would be appreciated!

CodePudding user response:

set value of kelompok_umur_id to 0 for all records first, then update your specific record, like:

...
$validatedData->update([
    'ku_name'        => $request->ku_name,
    'ku_description' => $request->ku_description,
]);

$staff = StaffPPA::where('kelompok_umur_id', 0)->first();
if( $staff ) {
    // set kelompok_umur_id to 0 for all rows using
    StaffPPA::query()->update(['kelompok_umur_id' => 0]);

    // now update the record you want as 
    $staff->update(['kelompok_umur_id' => $id]);
}
  • Related