Home > Software design >  Laravel update table
Laravel update table

Time:10-09

I'm trying to do simple function edit student table field, But its updating only first field: first_name

My controller.

    public function editStudent(Request $request)
{
    $studId = $request->get('studId');
    $studFirstName = $request->get('firstName');
    $studLastName = $request->get('lastName');
    $studGender = $request->get('gender');
    $studBirthday = $request->get('birthday'); 
    $studSchoolId = $request->get('schoolId'); 
    $update = Student::where('id', $studId)->update(['first_name' => $studFirstName],
    ['last_name' => $studLastName], ['gender' => $studGender], ['birthday', $studBirthday], ['school_id' => $studSchoolId]); 
    return response()->json([
        "update" => $update,
    ]);
}

CodePudding user response:

Update takes a single array, you're passing in multiple arrays

$update = Student::where('id', $studId)
    ->update([
        'first_name' => $studFirstName,
        'last_name' => $studLastName, 
        'gender' => $studGender, 
        'birthday'=> $studBirthday, 
        'school_id' => $studSchoolId
    ]);

CodePudding user response:

Its better to get the item from DB then update that on a second query:

$student = Student::find($studId);

$student->update([
    'first_name' => $request->firstName,
    'last_name' => $request->lastName, 
    'gender' => $request->gender, 
    'birthday'=> $request->birthday, 
    'school_id' => $request->schoolId
]);
  • Related