如果存在表单值,则仅更新字段

时间:2014-01-19 21:34:55

标签: laravel laravel-4 eloquent

我正在使用Form Model Binding并使用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();

哪个工作正常,但如果没有提供密码(因为用户不想更新/修改它),那么db中的密码字段设置为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()方法一样。

8 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分:3)

创建基本模型并覆盖更新功能,如

/**
 * @param array $attributes
 * @return mixed
 */
public function update(Array $attributes = array()){
    foreach($attributes as $key => $value){
        if(!is_null($value)) $this->{$key} = $value;
    }
    return $this->save();
}

使用后:

$model = Model::find($id);
$model->update(Input::only('param1', 'param2', 'param3'));

答案 2 :(得分:2)

选中此项,您可以验证输入中是否存在密码,并将其从质量分配中排除。您可以将Input :: except和Input ::仅用于此目的

public function update ($id) {
    $user = User::findOrFail ($id);
    if (Input::get ('password') == '') {
        $user->update (Input::except ('password'));
    }
    else {
        $user->update (Input::all ());
    }

    //return something
}

答案 3 :(得分:2)

$data = $request->password ? $request->all():$request->except('password');
$user->update($data);

如果密码不为空

,则只会更新密码

答案 4 :(得分:1)

我会坚持你的后一个例子。另一种选择是使用mutator检查那里的值,如果值为空则不更新。但在我看来,Eloquent不应该对此负责。

我也避免使用fill()的所有输入。只选择你想要的东西。

答案 5 :(得分:0)

这是Laravel(和其他框架)的一个非常糟糕和常见的问题。我的解决方案类似于之前的一些......

我总是将表单数据Input :: all()存储在update / store方法开头的变量中。由于您通常需要至少两次(验证和创建/更新),这似乎是一个很好的做法。然后使用它,在做任何其他事情之前,我在update()中检查是否存在密码,如下所示:

$aFormData = Input::all();

if ( !$aFormData['password'] )
  unset( $aFormData['password'] );

... the rest of your code here using $aFormData ;) ...

就是这样,希望它有所帮助!

答案 6 :(得分:0)

更清洁的方法是使用Eloquent Mutators

在任何情况下,您都不允许使用null或空字符串作为密码,因此您可以在Account模型中安全地定义以下mutator。

// Only accept a valid password and 
// hash a password before saving
public function setPasswordAttribute($password)
{
    if ( $password !== null & $password === '' )
    {
        $this->attributes['password'] = bcrypt($password);
    }
}

如果上面的mutator不是null并且是一个空字符串,那么它只会设置一个密码属性。它还会在保存之前对密码进行哈希处理,因此您无需在其他地方的控制器操作或应用程序中执行此操作。

答案 7 :(得分:0)

如诺曼·乌尔·雷曼(Noman Ur Rehman)所说,最好的办法是使用变体,但是他在代码中有错误。正确的是:

public function setPasswordAttribute($password){
   if ( $password !== null && $password !== '' )
      $this->attributes['password'] = Hash::make($password);
}
相关问题