senty senty - 23 days ago 7
PHP Question

Using Mimes for Validating Laravel File Post - Word File

I have a form that I post file. I am trying to use validation to accept only word documents. I tried using mime types however doesn't seem to work and I couldn't spot my mistake.

<form action="" method="post">
<div class="form-group{{ $errors->has('myFile') ? ' has-error' : '' }}">
<div class="col-xs-12">
<div class="form-material">
<input class="form-control" type="file" id="myFile" name="myFile">
<label for="myFile">MyFile</label>
@if ($errors->has('myFile'))
<div {{ $errors->first('myFile') }}</div>
@endif
</div>
</div>
</div>
</form>


This posts successfully and I receive it in my controller.

In my controller, I try to validate it, however it is always returning the error, even though the file is in '.doc' format.

public function myController(Request $request) {
$validator = MyValidations::myFormValidator($request->all());

if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}

...
}


and the validator:

public static function myFormValidator($data) {
return Validator::make($data, [
'myFile' => 'required|mimes:application/msword'

// I also tried
// 'myFile' => 'required|mimes:doc,docx'
]);
}





Edit: I have seen some posts on SO, regarding that there is a file
config > mimes.php
but I don't have it on Laravel 5.3

tam tam
Answer

Actually, there is nothing really wrong with your validation code. The problem is that your form is not submitting the files properly.

Add the proper enctype to your form like so:

<form action="" method="post" enctype="multipart/form-data">

Also make sure to get the syntax right for validation (but I think you knew this part). Use either of these two:

'myFile' => 'required|mimes:doc,docx'
'myFile' => 'required|mimetypes:application/msword'