plusone's avatar

Ignore dimension validation if uploaded file is not image

I have a file upload control, I want to set dimensions validation only if uploaded file is image. If pdf file is uploaded then want to ignore dimensions validations. Is there any way to do like this? or I have need to set separate file upload control for different types files.

$validator = Validator::make($request->all(), [
            'file' => 'required|mimes:xls,xlsx,pdf,jpg,jpeg,png|max:2048|dimensions:min_width=500,min_height=500,ratio=3/2',
        ]);
0 likes
4 replies
bobbybouwmann's avatar
Level 88

So in general I would recommend to keep these two validation separated. This way you can directory validate the files the way you want. Note that this requires some extra work. You have a few options here

  1. Create your own custom validation rule. You can then check if the given file is an image and handle the validation accordingly and also for the files.

Documentation: https://laravel.com/docs/5.6/validation#custom-validation-rules

  1. Use different validation rules based on the given input. So for example you check the mime type before you go into validation. So you might have code that looks like this
$file = $request->get('file');
$mimeType = $file->getMimeType();

$rules = [
    'file' => 'required|mimes:xls,xlsx,pdf|max:2048',
];

if (in_array($mimeType, $imageMimeTypes)) {
    $rules = [
        'file' => 'required|image|max:2048|dimensions:min_width=500,min_height=500,ratio=3/2',
    ];
}

$validator = Validator::make($request->all(), $rules);
  1. You can also do this on the client side. Instead of always posting to file you can decide to post with a key called file or a key called image. Each can then have their own validation rule. If you use sometimes it will only validate it when the key is available in the request.

Documentation: https://laravel.com/docs/5.6/validation#conditionally-adding-rules

plusone's avatar

Hi @bobbybouwmann

This solution won't work when user don't upload files and try to submit. Because getMimeType() called before required validation. So it is throwing error

"Call to a member function getMimeType() on null"

Is there anyway so we can check validation one by one? I mean first check required and then other validations.

Please or to participate in this conversation.