Custom Validation for files uploads

Submitted by venkat556 - 1 week ago

Sometimes we need to validate the files that are chosen. Even if its correct extension also will through error. It is possible to achieve this with a custom validation rule and then using it on the request with mime types.

// AppServiceProvider.php (or your preferred)

use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeExtensionGuesser;


    // ...

    // Extend the validation rule with the custom rule called 'file_types'
   public function boot()
    {
        //Custom validation for check the mime types
        Validator::extend('file_types', function ($attribute, $value, $parameters, $validator) {
            $extension = $value->getClientOriginalExtension();
            $guesser   = new MimeTypeExtensionGuesser();
            $mimetype  = $guesser->guess($value->getMimeType()); //$value->getClientMimeType()
            if (in_array($mimetype, $parameters) || in_array($extension, $parameters)) {
                return true;
            }
            return false;

        });
        //Custom validation message for check the mime types
        Validator::replacer('file_types', function ($message, $attribute, $rule, $parameters) {
            return str_replace(':values', implode(", ", $parameters), $message);
        });
    }

    // ...

// In your Controller, or wherever you build your validation set

// ...

            $rules['documents.*']  = 'file_types:doc,docx,pdf,svg,ppt,xls,xlsx,csv,pptx';
            $rules['image']  = 'file_types:jpg,png,gif,jpeg';

// ...
comments powered by Disqus