I am trying to update my template details in the controller. But currently, my code is not working. It is not updating the fields. Anyhow if I add $template->save(). It saves the updated record as a new record. How to make my current code work? Why I am facing this situation? Please, someone, explain to me and correct my code as still, I am learning Laravel. Thanks in advance.
update function in TemplateController
public function update(Request $request, $id) { if(! lara_club_has_permission('edit-template') ){ return view('403'); } $this->validate($request, [ 'title'=>'required', 'start_date'=> 'required', 'end_date'=>'required', 'template_content'=>'required', ] ); //check status response if(isset($request->status)&&$request->status=='on'){ $status='1'; }else{ $status="0"; } $template=new Template(); $template->title=$request->title; $template->start_date=convert_to_sql_date_format($request->start_date); $template->end_date=convert_to_sql_date_format($request->end_date); $template->is_active=$status; $template->template_content=$request->template_content; $input = $request->all(); $template->update($input); $name = $input['title']; return redirect()->route('templates.index')->with('success', 'Template <b>'. $name.'</b> Updated!'); }
Advertisement
Answer
you creating new object $template=new Template();
but you need to update existing one so try below code
$template=Template::find($id); //or use $template=Template::where('id',$id)->first(); $template->title=$request->title; $template->start_date=convert_to_sql_date_format($request->start_date); $template->end_date=convert_to_sql_date_format($request->end_date); $template->is_active=$status; $template->template_content=$request->template_content; $input = $request->all(); $template->update($input);