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

Best way to populate model on edit

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

    $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';
    }

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

protected $fillable = ['first_name', 'last_name', 'email'];

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

$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') );

但是,我会先检查这个输入。如果您传递的内容在您的 table(一列)中不存在..它会抛出异常。