仅在表单值存在时更新字段

编程入门 行业动态 更新时间:2024-10-07 16:26:31
本文介绍了仅在表单值存在时更新字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

这可以正常工作,但是如果未提供密码(因为用户不想更新/修改密码),则在数据库中将password字段设置为null.因此,如果表单中提供了新的密码值,我只希望密码字段更新.

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());

更多推荐

仅在表单值存在时更新字段

本文发布于:2023-10-23 02:28:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1519473.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   表单

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!