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

muuucho's avatar
Level 11

Validate number of uploaded files

The first validation rule works, but doesn't show any error message. Why?

public function rules(): array
    {
        return [
            'file_inputs' => 'required|array|max:4',
            'file_inputs.*' => 'required|file|mimes:pdf,jpg,png,gif|max:2048', 
        ];
    }
0 likes
3 replies
martinbean's avatar
Level 80

@muuucho We don’t know because we don’t know what data you’re submitting; and you don’t say what you expect to see, and what you actually see.

1 like
muuucho's avatar
Level 11

@martinbean Sorry about that. Like I say in my header, it is multiple files that I upload. When I upload more than 4 files at the same time, I expect to see an error in my blade file. Which led me to the solution. I only had the second validated element in the blade file:

@error('file_inputs.*') <span class="text-red-600">{{ $message }} </span>@enderror

Now I have this, and it's working, thanks! :-)

@error('file_inputs.*') <span class="text-red-600">{{ $message }} </span>@enderror
@error('file_inputs') <span class="text-red-600">{{ $message }} </span>@enderror
LaryAI's avatar
Level 58

The issue with your validation rules is that the max:4 rule is being applied to the array itself, but it doesn't actually limit the number of files in the array. Instead, you should use the bail rule to stop on the first failure and then use the array rule with min and max constraints to ensure the number of files is within the desired range.

Here's how you can modify your validation rules to properly validate the number of uploaded files and show an error message:

public function rules(): array
{
    return [
        'file_inputs' => 'required|array|min:1|max:4',
        'file_inputs.*' => 'required|file|mimes:pdf,jpg,png,gif|max:2048',
    ];
}

Explanation:

  • required|array|min:1|max:4: This ensures that file_inputs is a required field, it must be an array, and the array must contain between 1 and 4 items.
  • file_inputs.*: This applies the validation rules to each file in the file_inputs array, ensuring each file is required, is a valid file, has an allowed MIME type, and does not exceed the maximum file size of 2048 KB.

With these rules, if the number of files exceeds 4 or is less than 1, a validation error message will be shown. Additionally, each file will be individually validated for the specified constraints.

Please or to participate in this conversation.