bortz's avatar
Level 1

"required_without" validation rule not working as expected

I have a validation like this:

$this->validate($request, [
    'image_url' => ['required_without:image_upload', 'active_url'],
    'image_upload' => ['required_without:image_url', 'image'],
]);

What I would like it to do is that you can either enter an image URL or upload an image. If I enter an image URL, the validation goes through, as expected. However, if I leave the image_url empty and select an image to upload, I get the error message:

The image url is not a valid URL.

Why is this? It shouldn't even check that, because it's not required (since I uploaded an image).

0 likes
7 replies
MichalOravec's avatar
Level 75
$this->validate($request, [
    'image_url' => ['required_without:image_upload', 'sometimes', 'nullable', 'active_url'],
    'image_upload' => ['required_without:image_url', 'sometimes', 'nullable', 'image'],
]);
1 like
bortz's avatar
Level 1

Thanks! It works, but why?

The required without documentation states:

required_without:foo,bar,...

The field under validation must be present and not empty only when any of the other specified fields are not present.

So, in this case, image_url must be present and not empty only when image_upload is not present.

What am I missing? Could you please explain it? And why are sometimes and nullable necessary?

bortz's avatar
Level 1

Thanks for the answer but I still don't understand why sometimes and nullable are necessary. After running some tests, I concluded that this is enough:

$this->validate($request, [
    'image_url' => ['required_without:image_upload', 'nullable', 'active_url'],
    'image_upload' => ['required_without:image_url', 'image'],
]);

Apparently, if you provide an image url, it doesn't check the image upload. So far, so good.

If you provide an image upload, it still checks active_url on the image url and throws an error, since the image_url is present but empty. However, after adding nullable, it goes through and gives no error. No clue why it behaves like this.

bortz's avatar
Level 1

But still, according to the required without documentation, it shouldn't even check image_url if image_upload is provided...

bortz's avatar
Level 1

I think I figured out why nullable is still required: because when I leave the textbox image_url empty, it's not null, it's empty. So, while it's still not required because there's the image upload, the validation still sees it as being non-null and thus checks if it's an active url. I guess nullable here means either not set or set to empty.

Please or to participate in this conversation.