Laravel: Validate Fields Only When One Is Present

Sometimes, when setting up validation for Laravel forms, you need to be able to set up validation rules for two fields, but allow for one of them to be ignored if the other is filled. This is how you can set up your validation rules to make that happen:

'email' => 'nullable|required_without:login',
'login' => 'nullable|required_without:email'

You first have to set nullable to allow both fields to have null values, otherwise Laravel rejects them. After that, you set each field to require_without:[otherField]

A potential use case for this (and the one I needed it for) is when your application allows a user to login using an email, a login, or both. It turns out sometimes didn’t work at all for this because it only applies when the field in question sometimes isn’t sent, not cases where it is sent but the value is null. The solution above accounts for this.

No Comments

Post a Comment