D
D
Danbka2017-02-22 13:28:09
Laravel
Danbka, 2017-02-22 13:28:09

How to write a password validation rule when updating user information?

I have forms to add and edit user information (name, email, password, password confirmation).
What is the best way to validate the "password" and "password confirmation" fields if:
1) when adding a user, these fields are required
2) when changing, they are not required if they are not filled. But if they are filled, then you need to check their identity.
In general, the standard logic.
So far I have done this: when adding, the following rules are used:

public function rules()
{
    return [
      'name' => 'required|max:255',
      'email' => 'required|email|unique:users,email',
      'password' => 'required|min:6|confirmed',
      'password_confirmation' => 'required',
    ];
}

when updating:
public function rules()
{
    $userId = $this->route()->parameter('user');
    $password = $this->get('password');
    $rule = [
      'name' => 'required|max:255',
      'email' => [
        'required',
        'email',
        Rule::unique('users', 'email')->ignore($userId),
      ],
    ];
    if (!empty($password)) {
      $rule['password'] = 'required|min:6|confirmed';
      $rule['password_confirmation'] = 'required';
    }
    return $rule;
}

Those. if the password is entered, then we check it according to all the rules, if not, then no.
Question 2:
1) Is it possible to combine the rules when adding and updating into one?
2) Is it possible to somehow rewrite the update rule without the terrible if'a?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question