Search code examples
phplaravelvalidationfile-uploadmime

file mime type validation if file is uploaded in laravel


I have a file upload field as :

<input class="form-control" type="file" name="image[]" multiple="multiple">

This field is optional. User may add file or not.

I want file type validation and I don't want to allow user to add files other than images. This is I have done so far.

$this->validate($request,[
        'image.*' => 'mimes:jpg,jpeg,png,bmp,tiff |max:4096',
    ],$messages = [
        'mimes' => 'Please insert image only',
    ]);

But, when there is no file is uploaded, validation doesn't got passed. Any help appreciated.


Solution

  • As per Laravel 5.8

    For file validation using request data for required, mime type & file size check before uploading file:

    $validator = Validator::make($request->all(),[
            'image' => 'required|mimes:jpg,jpeg,png,bmp,tiff |max:4096',
        ],$messages = [
            'mimes' => 'Please insert image only',
            'max'   => 'Image should be less than 4 MB'
        ]);
    
    dd($validator->errors());
    

    Note: Don't forget to use Validator Facade