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

Saf*_*sen 1 eloquent laravel-4

我试图保存我的模型后收到此错误.这是我得到的错误:

调用未定义的方法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');
}
Run Code Online (Sandbox Code Playgroud)

我的Laravel版本是稳定版本.

Kou*_*sha 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');
}
Run Code Online (Sandbox Code Playgroud)

此外,您可以通过替换where($column, '=', $query)为简化查询构建

$user = User::whereCode($code)->whereActive(0)->first();
Run Code Online (Sandbox Code Playgroud)