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

时间:2015-04-23 10:25:10

标签: laravel eloquent laravel-5

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

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

3 个答案:

答案 0 :(得分:1)

您可以使用下面的质量分配

$inputUser = User::find($id);
$inputUser->fill(Input::all())
$inputUser->save();

确保您已在模型中设置$ fillable

protected $fillable = ['email', 'name'];

答案 1 :(得分:0)

首先,指定模型中可填写的属性(为了安全起见):

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

然后你可以从数组

创建模型
$user = new User(Input::all());

或更新

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

答案 2 :(得分:0)

你可以这样做:

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

但是,我会先检查这个输入。如果你传递了一些在你的表中没有的东西(一列)......它会抛出异常。