如果表单值存在,则仅更新字段 [英] Only update field if form value exists
问题描述
我正在使用表单模型绑定,并使用 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();
哪个工作正常,但如果没有提供密码(因为用户不想更新/修改它),那么密码字段在数据库中设置为空.因此,如果通过表单提供了新的密码值,我只希望密码字段更新.
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屋!