Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kokoshneta's avatar

Excluding a field from validation if not present, but validating type if present

[Laravel 9, Livewire 2 – upgrading is not currently an option]

I have a Livewire component that validates a number of fields belonging to a User model. The validation rules are stored in the User class and pulled into the component from there.

Usually, when validating User models, I want to validate the username and password fields, but for this particular component, those two fields are not present in the data at all, so they should not be validated. The rules are set up like this:

// User class
public function rules() {
  return [
    "name" => "required|string",
    [other rules…],
    "username" => ["sometimes", "required", "email", "unique:App\Models\User,username"],
    "password" => ["sometimes", "required", "confirmed", Password::defaults()],
  ];
}

When I validate the component form, the sometimes rule for the password works as intended: the password field is skipped because it’s not present.

It doesn’t work for the username, though: even though there is no username field in the data, I still get an error message that “The username must be a valid email address”. If I remove the email rule, it works, but then of course it won’t validate whether it’s a valid e-mail address when it is present.

How can I tell the Laravel validator to completely ignore and skip validation if the field is not present in the data, but otherwise validate according to all the rules given?

0 likes
6 replies
kokoshneta's avatar

As a temporary workaround, I’ve altered the rules in the Livewire component to exclude them completely:

// Livewire component
public function rules() {
  return array_merge($this->user->rules(), [
    'username' => 'exclude',
    'password' => 'exclude',
  ];
}

But this is a hack and a workaround – the real solution would be to fix the base rule, which I’m sure must be possible somehow.

Glukinho's avatar

even though there is no username field in the data

Are you sure username field is not present at all? It may be present but null for example.

Do dd($data) before validation to make sure.

kokoshneta's avatar

Yes, as I said, it is not there in the data. There is no field for the username or password on this page at all, and when I output $validator->getData(), they are not present.

Glukinho's avatar

No idea, sorry. Maybe you should test the same logic on recent Laravel/Livewire versions - if the problem is gone I'm afraid you don't have much options but your workaround.

By the way, the workaround you call "a hack" seems pretty clear and nice for me. Maybe it's not too bad.

ghabriel25's avatar

How about require_unless:username,null or exclude_if:username,null?

kokoshneta's avatar

Nope, that doesn’t prevent the validation either – it still fails the email rule.

Please or to participate in this conversation.