为什么update或save()在laravel 5.8中不起作用?

时间:2019-06-04 23:18:06

标签: php laravel react-native

我正在尝试更新表(从我的React Native应用程序获取到laravel),并且总是出现错误。这是我的获取方式:

fetch("http://192.168.2.45/backend/public/api/checkuser", {
      method: "POST",
      body: JSON.stringify(user),
      headers: new Headers({
        "Content-Type": "application/json"
      })
    })

我的laravel API:

Route::post('update','mainController@update');

 public function update(Request $request)
    {

        $email = $request->email;


        $error_message="DENIED";
        $Success = "Success";


       if (user::where('email', '=',$email)->count() > 0) {
        $user = user::where('email', '=',$email);
        $user->image_name = $request->email;
        $user->save()--->
      here i get my error
      ( i have also tried where(....)->update(....)
      and i get the same error)
          return response()->json(['message' => $Success]);
         }else{
           return response()->json(['message' => $error_message]);
       }
   }

2 个答案:

答案 0 :(得分:4)

使用lapply时返回的结果是where,而不是可以在其上调用CRUD操作的用户模型中的项。因此,您应该取回结果并调用保存,因此请用以下代码替换您的代码块:

Query Builder

要说明一下,if ($user = user::where('email', $email)->first()) { $user->image_name = $email; $user->save(); return response()->json(['message' => $Success]); } // no need for an else block return response()->json(['message' => $error_message]); 如果未找到记录,将返回first(),这表示null条件,它将返回您的错误消息,如果找到则将更新您的{{1 }}到电子邮件。 (这没有意义,但这是您的代码)

答案 1 :(得分:0)

更改查询。您的搜索未返回结果。

$user = user::where('email', $email)->first();
if(isset($user))
{
$user->image_name = $email;
$user->save();
return response()->json(['message' => $Success]);
}
else
return response()->json(['message' => $error_message]);