Laravel update only single row

Viewed 18711

I am having a trouble updating my single record in database with laravel.

When i run this method and give requestparams only "name" then the other fields are going to be blank in database. How to keep the values that are not specified in the requestparams?.

public function update(Request $request, $id)
{
    $user = User::find($id);
    if(!is_null($user)){
        $user->name = $request->input('name');
        $user->email = $request->input('email');
        $user->password = $request->input('password');
        $user->save();
    }else{
        $data = array('msg' => 'The user, you want to update, does not exist', 'error' => true);
        echo json_encode($data);
    }
}
5 Answers

You can do that like this.(Here 'posts' is Database Table name)

// write following statement in your model.
    use DB; 

     public function update($request, $id){
                $check = DB::Table('posts')->where('id',$id)->first(); 
                if(!is_null($check)){
                    $result =  DB::Table('posts')->where('id',$id)->update(
                    array(
                    'name' =>  $request->name,
                    'email' => $request->email,
                    'password' => $request->password
                    )
                    );
                    return $result = array('msg' => 'Updated successfully !! ', 'success' => true);
                }
                else{
                    return $result = array('msg' => 'User Not Found !! ', 'error' => true);
                }
            }
Related