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

noufalcep picture noufalcep · Mar 29, 2017 · Viewed 45.9k times · Source

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',
]);

Answer

Rejinderi picture Rejinderi · Mar 29, 2017

try using nullable as a rule

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

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