I'm building some forms where fields are populated with database data or defaults to Placeholder text if there is no data.
What I can't seem to figure out is: When a user deletes all data in form it wont save it back to the database as blank/null, it just carried the same value in the field...
Input:
<div class="form-group @if($errors->has('username')){{ 'has-error' }}@endif">
<div class="col-md-6">
<label for="username">Username</label>
@if($errors->has('username'))<span class="label-has-error">{{ $errors->first('username') }}</span>@endif
<input type="text" name="username" class="form-control" tabindex="1" @if($info->username) value="{{ e($info->username) }}" @else placeholder="Username" @endif>
</div>
</div>
Controller:
public function postSettings() {
$validator = Validator::make(Input::all(),
array(
'username' => 'required_without_all:location,fullname|min:3',
'fullname' => 'required_without_all:location,username',
'location' => 'required_without_all:fullname,username'
)
);
if($validator->fails()) {
return Redirect::route('settings')->withErrors($validator);
} else {
$user = User::find(Auth::user()->id);
if(Input::get('username')) {
$user->username = Input::get('username');
}
if(Input::get('fullname')) {
$user->fullname = Input::get('fullname');
}
if(Input::get('location')) {
$user->location = Input::get('location');
}
$user->save();
Flash::success('Settings have been updated');
return Redirect::route('settings');
}
Flash::error('Update was unsecessful, please try again!');
return Redirect::route('settings');
}
Any ideas on how I can achieve this?
Thanks, Jack.
The problem are if
statements.
You should try to change:
if(Input::get('username')) {
$user->username = Input::get('username');
}
if(Input::get('fullname')) {
$user->fullname = Input::get('fullname');
}
if(Input::get('location')) {
$user->location = Input::get('location');
}
into
$user->username = Input::get('username');
$user->fullname = Input::get('fullname');
$user->location = Input::get('location');
Now if those inputs are empty if
statement will return false, so assignment won't be done and finally you save into database exactly you got from it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.