我正在使用表單模型綁定,並使用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();
,工作正常,但如果沒有設置密碼供應(因爲用戶不希望更新/修改),那麼密碼字段在數據庫中設置爲空。所以,如果通過表單提供新的密碼值,我只想更新密碼字段。
我知道我能做到以下幾點:
// 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 :: all()的引用嗎?我找不到應該避免的任何推理。 –
如果您有其他可以通過批量分配填寫的'User'字段,則可以使用該列名稱創建任意字段,並且無需對其進行任何檢查即可更改該值。僅收集您打算利用的內容是一種很好的做法。 –
我明白,但正確使用模型的守護或可填充屬性(我已經完成)。那麼在Input :: all之間並手動填充字段本質上沒有安全風險。 –