调用未定义的方法Illuminate \ Database \ Query \ Builder :: save()?

时间:2014-08-18 22:44:26

标签: laravel-4 eloquent

我在尝试保存模型后遇到此错误。这是我得到的错误:

  

调用未定义的方法Illuminate \ Database \ Query \ Builder :: save()

这是我的代码:

public function getActivate ($code)
{
    $user = User::where('code','=',$code)->where('active','=',0);

    if ($user->count())
    {
        $user->first();
        //Update user to active state
        $user->active = 1;
        $user->code ='';

        if($user->save()) 
        {
            return Redirect::route('home')
                            ->with('global', 'Account Activated ! You can sign in ');
        }
    }

    return Redirect::route('home')
                    ->with('global', 'We could not activate your account. Try again later');
}

我的Laravel版本是稳定版本。

1 个答案:

答案 0 :(得分:5)

问题是您没有获得用户的第一个实例,而您只是在查询本身上调用save()

以下是更新后的代码:

public function getActivate ($code)
{
    $user = User::where('code','=',$code)->where('active','=',0)->first();

    if ($user)
    {
        //Update user to active state
        $user->active = 1;
        $user->code ='';

        if($user->save()) 
        {
            return Redirect::route('home')
                            ->with('global', 'Account Activated ! You can sign in ');
        }
    }

    return Redirect::route('home')
                    ->with('global', 'We could not activate your account. Try again later');
}

此外,您可以通过将where($column, '=', $query)替换为

来简化查询构建
$user = User::whereCode($code)->whereActive(0)->first();