gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 18:34:11 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com