Laravel 在编辑时填充模型的最佳方法

Laravel 在编辑时填充模型的最佳方法,laravel,eloquent,laravel-5,Laravel,Eloquent,Laravel 5,我不想手动设置每个属性,只想做类似的事情 $inputUser = Input::all(); $inputUser->save(); 但是,它不起作用 这是我的解决方案,我必须为空字段设置空值。此外,我的验证在模型文件中 $id = Auth::id(); $inputUser = Input::all(); $inputUser['id'] = $id; $user = new User(); $errors = array

我不想手动设置每个属性,只想做类似的事情

    $inputUser = Input::all();
    $inputUser->save();
但是,它不起作用

这是我的解决方案,我必须为空字段设置空值。此外,我的验证在模型文件中

    $id = Auth::id();

    $inputUser = Input::all();
    $inputUser['id'] = $id;

    $user = new User();
    $errors = array();

    // attempt validation
    if ($user->validate($inputUser))
    {
        $user = User::find($id);
        $user->id = $id;

        foreach($user->toArray() as $key => $value)
        {
            if (array_key_exists($key, $inputUser))
            {
                if (empty($inputUser[$key])) {
                    $user->{$key} = null;
                }
                else{
                    $user[$key] = $inputUser[$key];
                }
            }
        }

        if (Input::get('password') != ""){
            $user->password = Input::get('password');
        }

        $user->save();
        return 'success';
    }

首先,指定模型中可填充的属性(出于安全考虑):

然后可以从数组中创建模型

$user = new User(Input::all());
或者更新它

$user->fill(Input::all());

您可以像下面这样使用质量赋值

$inputUser = User::find($id);
$inputUser->fill(Input::all())
$inputUser->save();
只需确保在模型中设置了$fillable

protected $fillable = ['email', 'name'];
您可以这样做:

User::where('id', $userId )->update( Input::except('_token') );

但是,我会先检查这个输入。如果传递的是表(列)中不存在的内容,它将引发异常。

我尝试过,即使我将id设置为可填充,也会得到“SQLSTATE[23000]:完整性约束冲突:1062键“PRIMARY”的重复条目“1”。我设置$user->id=$id;我编辑了我的答案。如果您正在编辑用户,那么只需从DB加载雄辩的模型并使用->填充函数。您不应该更改和现有对象的ID。好的,它可以工作,我没有尝试从数据库中提取然后填充。然后,为了更新,我似乎必须执行两个查询。我没有看到现在我的密码被设置为空字符串,并且创建为Null。如何从更新中排除这些字段?Input::save()后的Exception('password','created_at'):我获取SQLSTATE[23000]:完整性约束冲突:1062键“PRIMARY”的重复条目“1”。我在save()之前设置了ID。似乎您的数据库中已经有了
ID=1
的内容(每个ID必须是唯一的)。Laravel会自动为您分配id,所以您不应该尝试填充它。
User::where('id', $userId )->update( Input::except('_token') );