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

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


In case column is nullable

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

@Rejinderi's answer is correct!

In case column is not nullable (This may help other)

'password' => 'sometimes|required|min:6|confirmed',

Result

username = 'admin',password = null // fail- requiredusername = 'admin',password = 123 // fail- min:6username = 'admin' // pass- validate only exist


This is how I would do it:

//For new or create :$this->validate($request, [    'name' => 'required|max:255',    'email' => 'required|email|max:255|unique:users',    'password' => 'required|min:6|confirmed',]);//For edit or update:$this->validate($request, [    'name' => 'required|max:255',    'email' => 'required|email|max:255|unique:users',    'password' => 'min:6|confirmed',//just remove required from password rule]);

Explanation:
This way the value will be validated only when it will be defined (present) in request
If you use nullable, than validator will accept null as value (which i assume is not acceptable)
If you remove password validation from update than this input will not be validated at all, and any value will be accepted (which is again not acceptable);