Home » Php » php – How to update data in Laravel controller?

php – How to update data in Laravel controller?

Posted by: admin February 25, 2020 Leave a comment

Questions:

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!');
    }
How to&Answers:

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);

Answer:

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();

Answer:

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);
}