why update or save() does not work in laravel 5.8?

Viewed 562

I am trying to update table (fetching from my react native app to laravel) and i always get error. This is how i fetch:

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

my 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 Answers

When you use where the result back is a Query Builder and not an item of your user model on which you can call CRUD operations. So you should get the result back and call save on it, so replace your block with this one:

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

And to explain first() will return null if a record is not found, which means false condition and it will return your error message, if found it will update your image_name to the email. (Which does not make sense, but it is your code)

Change the query.Your search not returning results.

$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]);
Related