2016-05-10 21 views
0

我一直在嘗試使用post請求更新差點評分。但我似乎得到一個錯誤:從空值創建默認對象。使用api調用更新laravel的值

代碼:

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

     } 
    } 

如果用戶沒有在盤口表,則使用else塊代碼運行存在和其他用戶創建一個差點得分,如果塊需要執行和更新得分。我嘗試了很多選擇,但似乎沒有得到它的工作。不知道我做錯了什麼。

我使用return檢查了$ user,$ handicap變量。這些變量有我需要添加到表中的信息。它只是它沒有更新。

回答

1

你的問題可能來自你有Handicap::find($user->id)行。顯然它是空的,因爲沒有找到這樣的模型,即使你的if語句返回true

在您的if聲明中您有where('user_id' , '=', $user->id),但您使用的是Handicap::find($user->id),這基本上是Handicap::where('id', '=', $user->id)->first()

嘗試將其更改爲:

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

+0

謝謝它的作品! –

0

您可以將此給出一個嘗試:

public function handicap(Request $request) 
{ 
    $validator = Validator::make(Input::all(), [ 
     'handicap' => 'required' 
    ]); 

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

    $handicap = Handicap::firstOrNew([ 
     'user_id' => $request->user()->id; 
    ]); 
    $handicap->user_id = $request->user()->id; 
    $handicap->handicap = $request->handicap; 
    $handicap->save(); 

    return response()->json(['msg' => 'You have successfully updated your handicap score!'], 200); 
} 
+0

是'$請求 - > handicap'爲'$請求 - >輸入( '差點')'或只是一個錯字的簡寫? –

+1

這不是拼寫錯誤..所有請求輸入都可以作爲類屬性訪問 –

+0

我收到此錯誤:SQLSTATE [23000]:完整性約束違規:1452無法添加或更新子行:外鍵約束失敗('usg' ('66') –