仅在表单值存在时更新字段 [英] Only update field if form value exists

查看:70
本文介绍了仅在表单值存在时更新字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用表单模型绑定,并使用fill()和save()方法更新数据库.

I'm using Form Model Binding as such and updating my DB using the fill() and save() methods.

{{ Form::model($account) }}
  {{ Form::text('name', null, array('class'=>'class')) }}
  {{ Form::text('email', null, array('class'=>'class')) }}
  {{ Form::password('password', array('class'=>'class')) }}
  {{ Form::password('password_confirmation', array('class'=>'class')) }}
{{ Form::close() }}

哪个触发了我的editAccount控制器方法:

Which fires my editAccount controller method:

$rules = array(
  'name' => array('required'),
  'email' => array('required'),
  'password' => array('confirmed')
);

$validator = Validator::make(Input::all(), $rules);

if ($validator->fails())
{
 // Redirect
}

// Save to DB
$account->fill(Input::all());
$account->save();

这可以正常工作,但是如果未提供密码(因为用户不想更新/修改密码),则在数据库中将password字段设置为null.因此,如果表单中提供了新的密码值,我只希望密码字段更新.

Which works fine, but if no password was supplied (because the user doesn't want to update/modify it) then the password field is set to null in the db. So, I only want the password field to update if a new password value is supplied via the form.

我知道我可以执行以下操作:

I know I can do the following:

// Set the fields manually
$account->name = Input::get('name');
$account->email = Input::get('email');

// Only update the password field if a value is supplied
if (Input::get('password')) {
    $account->password = Input::get('password');
}
$account->save();

但是我想知道是否有更清洁的方法来处理此问题?就像Laravel/Eloquent中的UpdateOnlyIfValueExists()方法一样.

However I'm wondering if there is a more cleaner way to handle this? Like an UpdateOnlyIfValueExists() method within Laravel/Eloquent.

推荐答案

使用Input::only('foo', 'bar')将仅获取完成请求所需的值-而不使用Input::all().

Using Input::only('foo', 'bar') will grab only the values needed to complete the request - instead of using Input::all().

但是,如果输入中不存在'foo'或'bar',则该键将以null的值存在:

However, if 'foo' or 'bar' doesn't exist within the input, the key will exist with the value of null:

$input = Input::only('foo', 'bar');
var_dump($input);

// Outputs
array (size=2)
  'foo' => null
  'bar' => null

要以一种干净的方式进行过滤,请过滤任何具有null值的值:

To filter in a clean way, any values with a null value:

$input = array_filter($input, 'strlen');

在您的示例中,它将替换为:$account->fill(Input::all());

In your example, this would replace: $account->fill(Input::all());

这篇关于仅在表单值存在时更新字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆