Laravel 5 validate csv file error on valid file type
20,887
Solution 1
Try changing
$validator = Validator::make(
[
'file' => $file,
'extension' => strtolower($file->getMimeType()),
],
[
'file' => 'required|in:csv',
]
);
To
$validator = Validator::make(
[
'file' => $file,
'extension' => strtolower($file->getClientOriginalExtension()),
],
[
'file' => 'required',
'extension' => 'required|in:csv',
]
);
Solution 2
If you're uploading a CSV file, you should allow the following mime types:
'application/vnd.ms-excel','text/plain','text/csv','text/tsv'
Also in Laravel 5:
$rules = [
'file' => 'required',
'extension' => 'required|mimes:csv'
];
From the docs: (http://laravel.com/docs/5.0/validation)
The Validator class provides several rules for validating files, such as size, mimes, and others. When validating files, you may simply pass them into the validator with your other data.
Solution 3
//custom vaildation for csv file
$this->validate(request(), [
'file' => ['required',function ($attribute, $value, $fail) {
if (!in_array($value->getClientOriginalExtension(), ['csv','xsl','xsls'])) {
$fail('Incorrect :attribute type choose.');
}
}]
]);
Author by
Swaraj Giri
Programmer on weekdays, photographer on weekends.
Updated on November 22, 2020Comments
-
Swaraj Giri over 3 years
I am trying to validate an uploaded csv file with
$validator = Validator::make( [ 'file' => $file, 'extension' => strtolower($file->getMimeType()), ], [ 'file' => 'required|in:csv', ] );
The validator fails on giving a valid csv file with message
The file must be a file of type: csv.
The validator passes if i remove
in:csv
.Am i doing something wrong?
PS -
$file
is available and of standard upload file typeobject(Symfony\Component\HttpFoundation\File\UploadedFile)
-
Swaraj Giri about 9 yearsTried that. Gives the same error. PS - I am using Laravel 5
-
Chris Townsend about 9 yearsOkay what is the error when using mimes? Also why are you not using a request for your validation, if using Laravel 5
-
Chris Townsend about 9 yearsOkay I see what you are doing now,
-
zeros-and-ones about 8 yearshow to get this in Request object?
-
Aamir almost 8 yearswhat is $file ?? what you storing in $file ?
-
Adam Pery almost 4 yearsThis is the best answer
-
Admin over 3 yearsNo need to do any extra thing, you just copy above code & use. its work for any type of mimes validation.
-
Harsh Patel over 2 yearsit's works perfectly. thanks +1