使用api调用更新laravel中的值

时间:2016-05-10 12:54:54

标签: php mysql 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);
            }

        }
    }

如果Handicap表中不存在用户,则else块代码运行并为用户创建障碍分数if块需要执行并更新分数。我尝试了很多替代方案,但似乎没有让它发挥作用。不知道我做错了什么。

我使用return检查了$ user,$ handicap变量。这些变量具有我需要添加到表中的信息。它只是它没有更新。

2 个答案:

答案 0 :(得分:1)

您的问题可能来自Handicap::find($user->id)行。显然它是null,因为找不到这样的模型,即使你的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();

答案 1 :(得分: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);
}