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

etfz's avatar

Validate empty input as not present?

Hi,

I have a simple form for uploading files, which can be done either by selecting a local file (<input type="file">) or by entering a URL. (<input type="url">) To that end, I validate the request like so:

$request->validate([
	'image' => [ 'image', 'required_without:url' ],
	'url' => [ 'url', 'required_without:image' ],
]);

This works fine when submitting a URL, but I have recently discovered that when uploading a file, the URL field also gets passed, and is received in Laravel as null, failing the validation. It seems like I can set the url field as nullable, and then check whether it isset, rather than request->has, which I've been doing so far, but I'm unsure of whether there is a better solution that I'm missing.

0 likes
6 replies
Snapey's avatar

input fields are always sent. only checkboxes are not sent when not checked.

Laravel will then convert empty strings to null.

Have you tried adding nullable to the url validation?

etfz's avatar

@Snapey Right. Then, am I to understand that a validation rule such as required_with[out]:some_input_field is pointless? I suppose required_if:some_input_field,null should work.

etfz's avatar

Nevermind. I think I've misunderstood, and the required rules already take null into consideration, so nullable is actually all I need, I think.

krisi_gjika's avatar

if you want to not check the url or image rule when the field is empty you can specify the nullable validation to both.

If you want to check in your controller how to handle each case you can use $request->filled('...') and decide what to do with the value when it's not "empty"

etfz's avatar

@krisi_gjika I don't really want them to be nullable, though. I think what I need is required_if, as per my other reply. $request->filled is what I need rather than $request->has, in any case. Thanks! I suppose, ideally I would combine this and use something like this:

$request->validate([
	'image' => [ 'image', Rule::requiredIf(!$request->filled('url')) ],
	'url' => [ 'url', 'required_without:image', 'nullable' ],
]);

Edit: Ok, the url field does need to be nullable, of course, since I can't prevent it being included in the request.

duk3's avatar

@etfz hey, you can also do PHP's is_null built-in function in your requiredIf above, as an argument, pass $request->input('url')

whatever feels more readable for you

Please or to participate in this conversation.