PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 23, 2022

[FIXED] How to update data in Laravel controller?

 October 23, 2022     laravel, laravel-controller, php, sql-update     No comments   

Issue

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

Solution

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


Answered By - Hamelraj
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing