Mirsad Batilovic Mirsad Batilovic - 5 months ago 24
PHP Question

Laravel 5 validation rule required_with:password_confirmation

I have a problem with validation rule in edit form. My form fields are

name
,
email
,
password
and
password_confirmation
. My
UpdateUserRequest
class return this rules:

return [
'name' => ['required', 'max:50', 'min:3'],
'email' => ['required', 'email', 'unique:users,email,' .$this->route('users')],
'password' => ['required_with:password_confirmation', 'confirmed']
];


And update method in
UsersController
is:

public function update(Requests\UpdateUserRequest $request, $id)
{
$user = $this->users->findOrFail($id);
$user->fill($request->only('name', 'email', 'password'))->save();
return redirect(route('backend.users.edit', $user->id))->with('status', 'User has been updated.');
}


And this is a form:



{!! Form::model($user, [
'method' => $user->exists ? 'put' : 'post',
'route' => $user->exists ? ['backend.users.update', $user->id] : ['backend.users.store']
]) !!}

<div class="form-group">
{!! Form::label('name') !!}
{!! Form::text('name', null, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
{!! Form::label('email') !!}
{!! Form::email('email', null, ['class' => 'form-control']) !!}
</div>

<div class="form-group">
{!! Form::label('password') !!}
{!! Form::password('password', ['class' => 'form-control']) !!}
</div>

<div class="form-group">
{!! Form::label('password_confirmation') !!}
{!! Form::password('password_confirmation', ['class' => 'form-control']) !!}
</div>

{!! Form::submit($user->exists ? 'Save User' : 'Create New User', ['class' => 'btn btn-primary btn-sm']) !!}





Password validate rule
required_with:password_confirmation
should allow user to leave empty fields
password
and
password_confirmation
if he does not want to change it, but this doesn't work. When I leave the field empty, the empty value is hashed and stored in database. All other validations work fine, but not when user leaves empty value in
password
and
password_confirmation
. Why this isn't working? What am I doing wrong?

Answer

You will need to updated the db seperate without using fill etc as it will always get the password value empty or not and then add it, so try:

   $user = $this->users->findOrFail($id);
   $user->name = $request->get('name');
   $user->email = $request->get('emil');
   if(!empty($request->get('password')) {
        $user->password = $request->get('password');
   }
   $user->save();

Something like that so you are checking if the PW needs to also be updated etc.

Basically you need to verify if it need to be entered or not, your method takes all the requested values and will update no matter if they are empty or note.