How to update on relevant fields in Laravel

I have a courses table and it has 4 fields namely – id, title, description, deadline.

I want to update only description and deadline, but what i have currently done queries the table by its id and updates all the fields.

How can i update only my description and deadline fields?

public function editCourse(Request $request, $id){          // first check whether a course in that id exists to be updated          $course = CourseModel::find($id);           // if there is no such course          if(is_null($course)){              return response()->json(["message" => "Record Not found!"],404);          }            // update the database          $course->update($request->all());          return response()->json($course,200); } 
Add Comment
2 Answer(s)

You can use save() method for updating certain field :

public function editCourse(Request $request, $id){          // first check whether a course in that id exists to be updated          $course = CourseModel::find($id);          // if there is no such course          if(is_null($course)){              return response()->json(["message" => "Record Not found!"],404);          }          // update only description and deadline          $course->description = $request->description;          $course->deadline = $request->deadline;          $course->save();          return response()->json($course,200); } 
Add Comment

There are a couple different ways to do this:

  1. Use the only method on the $request.
    Course::where('id', $id)->update($request->only(['description', 'deadline'])); 
  1. You can load up the model, alter its fields manually and save it, like:
    $course = CourseModel::find($id);     $course->description = $request->input('description');     $course->deadline = $request->input('deadline');     $course->save(); 

Both of those answers assume you are receiving the fields description and deadline in your request.

Answered on July 16, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.