Search code examples
phplaravellaravel-5.4laravel-validation

How to validate an input field if value is not null in Laravel


I am trying to create and update users with laravel 5.4

This is the validation added for create user. It works.

$this->validate($request, [
    'name' => 'required|max:255',
    'email' => 'required|email|max:255|unique:users',
    'password' => 'required|min:6|confirmed',
]);

On update the password field is not required. But validate the min:6 and confirmed rule if the password field is not null. Tried with sometimes.. but not working..

$this->validate($request, [
    'name' => 'required|max:255',
    'email' => 'required|email|max:255|unique:users,email,'.$id,
    'password' => 'sometimes|min:6|confirmed',
]);

Solution

  • try using nullable as a rule

    'password' => 'nullable|min:6|confirmed',
    

    see https://laravel.com/docs/5.8/validation#a-note-on-optional-fields