laravel - 仅当表单值存在时才更新字段

标签 laravel laravel-4 eloquent

我正在使用表单模型绑定(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/

相关文章:

php - laravel递归显示按级别/深度推荐的用户

laravel - Sentry 2、修改密码功能

php - Laravel 存储库模式契约

php - 如何根据数组的长度循环数组

Laravel 4 - Eloquent 结果仅在分配到另一个对象内部时显示(时间戳、递增、存在)

laravel - 如何提高电子邮件的稳健性? [邮件枪,laravel]

validation - 使用Laravel在验证期间检查输入中是否存在字段

php - 我怎样才能理顺 Laravel blade @extends 的执行顺序?

Laravel Eloquent 限制和偏移

模块目录内 Controller 的 Laravel 5.8 路由