Murlidhar Fichadia Murlidhar Fichadia - 6 months ago 24
PHP Question

updating value in laravel using api call

I have been trying to update the handicap score using a post request. But I seem to get an error saying : creating default object from empty value.

Code :

public function handicap(Request $request)
{
$user = Auth::user();

$rules = array(
'handicap' => 'required'
);
$validator = Validator::make(Input::all(), $rules);

// process the login
if ($validator->fails())
{
return response()->json(['msg' => 'Failed to update Handicap score!'], 200);
}
else {

if(Handicap::where('user_id', '=', $user->id)->exists())
{
$handicap = Handicap::find($user->id);
$handicap->user_id = $user->id;
$handicap->handicap = $request->input('handicap');
$handicap->save();
return response()->json(['msg' => 'You have successfully updated your handicap score!'], 200);
}
else
{
$handicap = new Handicap;
$handicap->user_id = $user->id;
$handicap->handicap = $request->input('handicap');
$handicap->save();
return response()->json(['msg' => 'You have added your handicap score successfully!'], 200);
}

}
}


If user does not exist in Handicap table then the else block code runs and creates a handicap score for the user else the if block needs to execute and update the score. I tried many alternatives but dont seem to get it working. Dont know what am I doing wrong.

I checked the $user, $handicap variables using return. those variables have the info that I need to add to the table. Its just that Its not updating.

Answer

Your problem probably comes from the line you have Handicap::find($user->id). Obviously it's null, because such model was not found, even though your if statement returns true.

In your if statement you have where('user_id' , '=', $user->id), but you are using Handicap::find($user->id) which is basically Handicap::where('id', '=', $user->id)->first().

Try changing it to:

$handicap = Handicap::where('users_id', '=', $user->id)->first();