作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在使用表单模型绑定(bind),并使用 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 Controller 方法:
$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();
这工作正常,但如果没有提供密码(因为用户不想更新/修改它),则密码字段在数据库中设置为空。因此,我只希望在通过表单提供新密码值时更新密码字段。
我知道我可以执行以下操作:
// 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());
关于laravel - 仅当表单值存在时才更新字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21222964/
我是一名优秀的程序员,十分优秀!