我使用这样的表单模型绑定,并使用fill()和save()方法更新数据库。
{{ 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控制器方法:
$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();
效果很好,但是如果未提供密码(因为用户不想更新/修改密码),则在数据库中将密码字段设置为null。因此,如果通过表单提供新的密码值,我只希望密码字段更新。
我知道我可以执行以下操作:
// 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()方法一样。
使用Input::only('foo', 'bar')
将仅获取完成请求所需的值-而不是使用Input::all()
。
但是,如果输入中不存在'foo'或'bar',则该键的值将为null
:
$input = Input::only('foo', 'bar');
var_dump($input);
// Outputs
array (size=2)
'foo' => null
'bar' => null
要以一种干净的方式进行过滤,请使用带有null
值的任何值:
$input = array_filter($input, 'strlen');
在您的示例中,它将替换为: $account->fill(Input::all());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句