Search code examples
laravellaravel-validation

How to validate a data field with exclude_if in Laravel?


I want to validate thumbnail field. When user upload the file with mime type is pdf the thumbnail is required. then, if user upload the photo which mime type is not pdf. thumnail field is not required.

Here is the code I have tried:

  'file' => 'required|mimes:jpg,jpeg,pdf|max:2048',
  'thumbnail' => 'exclude_if:file,mimes:pdf|required'

I know that the validate on thumbnail was not correct. Can anyone help me?


Solution

  • So you basically require thumbnail if mime type is pdf , you can use required_if validation. First add

    use Illuminate\Validation\Rule;
    

    Then,

    Validator::make($request->all(), [
         'file' => 'required|mimes:jpg,jpeg,pdf|max:2048',
         'thumbnail' => Rule::requiredIf(function () use ($request) {
              if ($request->file->getMimeType() == 'application/pdf') {
                     return true;
               } else return false;
          }),
    ]);