laravel上的更新记录不止一次

时间:2016-06-16 17:37:14

标签: laravel

我正在尝试更新laravel中的值。我有一个userupdate配置文件api,我可以使用给定的参数及其值第一次更新值,但第二次更新相同的值时,它给我的用户配置文件不存在。

我的代码是:

  public function UpdateUserProfile(Request $request)
  {

    $id = $request->input('id');
    $client_gender = $request->input('client_gender');
    $client_age = $request->input('client_age');
    $client_weight = $request->input('client_weight');
    $client_height = $request->input('client_height');
    $client_dob = $request->input('client_dob');

   $profile= DB::table('clients')
        ->where('id',$id)
        ->update(['client_gender'=>$client_gender,'client_age'=>$client_age,'client_height'=>$client_height,'client_weight'=>$client_weight,'client_dob'=>$client_dob]);
    if($profile)
    {
        $resultArray = ['status' => 'true', 'message' => 'User profile updated Successfully!'];
        return Response::json( $resultArray, 200);
    }
        $resultArray = ['status' => 'false', 'message' => 'User profile does not exist!'];
        return Response::json($resultArray, 400);}

第一次更新值时,它会给我这样的响应:

  {
"status": "true",
"message": "User profile updated Successfully!"
  }

当我通过邮递员点击更新请求时,它会给出400 Bad请求并且响应是:

{
"status": "false",
"message": "User profile does not exist!"
}

1 个答案:

答案 0 :(得分:1)

我建议重写该功能,如下所示;主要是因为它读得更好并且使用了Laravel中更常见的Model方法

public function UpdateUserProfile(Request $request)
{
    // this code fails if there is no client with this id
    $client = App\Client::findOrFail($request->id);

    // attach new values for all of the attributes
    $client->client_gender = $request->input('client_gender');
    $client->client_age = $request->input('client_age');
    $client->client_weight = $request->input('client_weight');
    $client->client_height = $request->input('client_height');
    $client->client_dob = $request->input('client_dob');

    // save
    $client->save();
    return ['status' => 'true', 'message' => 'User profile updated Successfully!'];
}