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.');
        }
    }]
]);
Share:
20,887
Swaraj Giri
Author by

Swaraj Giri

Programmer on weekdays, photographer on weekends.

Updated on November 22, 2020

Comments

  • Swaraj Giri
    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 type object(Symfony\Component\HttpFoundation\File\UploadedFile)

  • Swaraj Giri
    Swaraj Giri about 9 years
    Tried that. Gives the same error. PS - I am using Laravel 5
  • Chris Townsend
    Chris Townsend about 9 years
    Okay what is the error when using mimes? Also why are you not using a request for your validation, if using Laravel 5
  • Chris Townsend
    Chris Townsend about 9 years
    Okay I see what you are doing now,
  • zeros-and-ones
    zeros-and-ones about 8 years
    how to get this in Request object?
  • Aamir
    Aamir almost 8 years
    what is $file ?? what you storing in $file ?
  • Adam Pery
    Adam Pery almost 4 years
    This is the best answer
  • Admin
    Admin over 3 years
    No need to do any extra thing, you just copy above code & use. its work for any type of mimes validation.
  • Harsh Patel
    Harsh Patel over 2 years
    it's works perfectly. thanks +1