Laravel multiple file upload validation

2020-05-03 12:03发布

I am currently working in a form.

I have some issue with multiple file upload validation. I have only one field in a form which allows multiple file upload.

<input type="file" name="file[]" multiple="multiple">

And this is my validation,

$this->validate($request, [
    'file' =>'required',
    'file.*' => 'required|mimes:pdf,jpeg,png |max:4096',
],
 $messages = [
            'mimes' => 'Only PDF, JPEG, PNG are allowed.'
        ]
);

The validation works perfectly but I am not able to display error messages in blade file.

Here are my attempts.

@if($errors->has('file'))
    <span class="help-block">
        <strong>{{$errors->first('file')}}</strong>
    </span>
@endif

This is for displaying error if no file is uploaded.

Suppose I have uploaded following files,

abc.jpg
abc.html
abc.pdf

When mimes type validation throws error I am not able to display error message. Here in this case, error is thrown as $error->first(file.1) since validation fails at index 1

This index can be any index according to files uploaded and $error->first(file.*) doesn't work as well.

When I display all error after adding invalid files only from form, I've got these errors.

 Only PDF, JPEG, PNG are allowed.
 The type field is required. 
 The number field is required.
 The expiry date field is required. 

Any one have idea about this. Any help is appreciated.

Thanks,

3条回答
迷人小祖宗
2楼-- · 2020-05-03 12:50

You can use check for the images.

$errors->has('file.*')
查看更多
兄弟一词,经得起流年.
3楼-- · 2020-05-03 12:52

Try like this to validate

'file.*.mimes' => 'Only PDF, JPEG, PNG are allowed.',
查看更多
虎瘦雄心在
4楼-- · 2020-05-03 12:58

This is not the good way, but it's fine for my case.

I have validation rules

'file' =>'required',
'file.*' => 'required|mimes:pdf,jpeg,png |max:4096',

And, Error message

'file.*' => 'Only PDF, JPEG, PNG are allowed.'

Since I have only one file upload field, I have just checked this error message in a list of all messages and then displayed as follows.

<input type="file" name="file[]" multiple="multiple">
@foreach($errors->all() as $error)
    @if($error=="Only PDF, JPEG, PNG are allowed.")
            <span class="help-block"><strong>{{$error}}</strong></span>
    @endif
@endforeach

Thanks to all guys,

查看更多
登录 后发表回答