Muhammad
Muhammad

Reputation: 634

How to validate file types in Laravel

I am uploading a file on Laravel, and its validation doesn't seem to be working.

My controller code is as follows:

public function cv(Request $request) {
    if ($request->hasFile('cv')) {
        $file = $request->file('cv'); //i need this later to upload the file
        $rules= [
             'cv' => 'mimes:application/msword,text/plain,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        ];
        $x = $request->all();
        $validator=Validator::make($x, $rules);
        if ($validator->passes()){
            dd("Passes");
        }else{
            dd("fails");
        }
}}

My html code for my file is: <input type='file' name='cv'><br>

For some reason this code seems to fail, and the validator passes only if the file is a pdf. I only want the user to upload pdf files, doc files, docx files, amd text/plain files. When I attempt to upload a microsoft doc file, it fails. Could someone help me out, I am unsure what I am doing incorrectly.

Upvotes: 0

Views: 7968

Answers (3)

Marc DePoe
Marc DePoe

Reputation: 43

As per the documentation, mimetypes should be used when specifying the mime types as you are, whereas mimes should be used to specify file extensions. HTH!

Upvotes: 1

softfish
softfish

Reputation: 53

Maybe try this instead:

'cv' => 'mimes:pdf'

https://laravel.com/docs/5.5/validation#rule-mimes

Upvotes: 1

Niklesh Raut
Niklesh Raut

Reputation: 34924

I think you reversed params

 $validator=Validator::make($x, $rules);

Upvotes: 2

Related Questions