1
votes

I am working on a laravel project with user login. The admin can create new users and edit existing users. I have got a password and a passwordConfirm field in the update-user-form. If the admin puts a new password in the form, it should check for validation and update the record in the db. If not, it shouldn't change the password (keep old one), but update the other user data (like the firstname).

If I try to send the form with an empty password and passwordConfirm field, it doesn't validate. I got a validation error, that the password must be a string and at least 6 characters long, but I don't know why. It seems like the first line of my update function will be ignored.

UserController.php

public function update(User $user, UserRequest $request) {

    $data = $request->has('password') ? $request->all() : $request->except(['password', 'passwordConfirm']);

    $user->update($data);

    return redirect('/users');
}

UserRequest.php

public function rules() {
    return [
        'firstname' => 'required|string|max:255',
        'lastname' => 'required|string|max:255',
        'email' => 'required|string|email|max:255',
        'password' => 'string|min:6',
        'passwordConfirm' => 'required_with:password|same:password',
    ];
}
2

2 Answers

5
votes

If you want to validate a field only when it is present then use sometimes validation rule in such cases.

Add sometimes validation to both password & passwordConfirm. Remove the $data line from update();

// UserController.php

public function update(User $user, UserRequest $request) {

    $user->update($request->all());

    return redirect('/users');
}

// UserRequest.php
public function rules() {
    return [
        'firstname' => 'required|string|max:255',
        'lastname' => 'required|string|max:255',
        'email' => 'required|string|email|max:255',
        'password' => 'sometimes|required|string|min:6',
        'passwordConfirm' => 'sometimes|required_with:password|same:password',
    ];
}

Reference - https://laravel.com/docs/5.4/validation#conditionally-adding-rules

1
votes

I always do this in my projects:

//Your UserController file
public function update(User $user, UserRequest $request) {

    $user->update($request->all());

    return redirect('/users');
}

//Your UserRequest file

public function rules() {
$rules= [
    'firstname' => 'required|string|max:255',
    'lastname' => 'required|string|max:255',
    'email' => 'required|string|email|max:255'
];

  if($this->method()=="POST"){
   $rules['password']='sometimes|required|string|min:6';
  $rules['passwordConfirm']='sometimes|required_with:password|same:password';
  }
 return $rules;
} 

So, as you can see if your method is POST it means that you want to add a new user so its going to ask for password and passwordConfirm but if your method is PATCH or PUT it means you don't need to validate password and passwordConfirm.

Hope it helps