Reputation: 171
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!');
}
Upvotes: 1
Views: 3567
Reputation: 1
In my case , I am using like this..
public function update(Request $request, $id){
$employee = Employee::find($id);
$employee->name=$request->name;
$employee->email=$request->email;
$employee->phone=$request->phone;
$input = $request->all();
$employee->update($input);
//$validated = $this->validateEmployee($request);
//Employee::update($validated);
return response()->json('Data Updated');
}
Upvotes: 0
Reputation: 11
In my case I specify the table name in the method name, like this.
public function update(Request $request, Template $id)
{
$id->title=$request->title;
$id->start_date=convert_to_sql_date_format($request->start_date);
$id->end_date=convert_to_sql_date_format($request->end_date);
$id->is_active=$status;
$id->template_content=$request->template_content;
$input = $request->all();
$id->update($input);
}
Upvotes: 1
Reputation: 3972
You should use Laravel find
method, instead of declaring a new instance of it.
It should be
$template=Template::find($id);
Not
$template=new Template();
Upvotes: 1
Reputation: 4826
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);
Upvotes: 1