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); }
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); }
There are a couple different ways to do this:
- Use the only method on the $request.
Course::where('id', $id)->update($request->only(['description', 'deadline']));
- 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.