How to check input field if value is not null in Laravel

I am trying to create and update users using laravel 5.4

This is the confirmation added to create the user. He works.

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

      

No password is required when updating the field. But confirm min: 6 and confirm the rule if the password field is not null. Tried sometimes

.. but didn't work ..

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

      

+3


source to share


3 answers


try to use nullable generally

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

      



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

+12


source


Create rules based on the password field. Confirm only if the password field is present.



if ($request->input('password')) {
    $rules = [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users,email,'.$id,
        'password' => 'required|min:6|confirmed',
    ];
} else {
    $rules = [
        'name' => 'required|max:255',
        'email' => 'required|email|max:255|unique:users,email,'.$id
    ];
}

$this->validate($request, $rules);

      

0


source


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:
So the value will only be validated when it is defined (present) in the request
If you use with a null value than the validator will accept null as a value (which I assume is not acceptable)
If you remove the confirmation password from the update than this the input will not be checked at all, and any value will be accepted (which is again unacceptable);

0


source







All Articles