Search code examples
laravellaravel-8laravel-validation

Laravel Dynamically generated field validation


I have a form that submits a large number of images, let's say there are 5 images. I named them img1,img2..,img5. for now I am validating those fields one by one.

my validation code

$rules = [
            'image1' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:3072',
            'image2' => 'image|mimes:jpeg,png,jpg,gif,svg|max:3072',
            'image3' => 'image|mimes:jpeg,png,jpg,gif,svg|max:3072',
            'image4' => 'image|mimes:jpeg,png,jpg,gif,svg|max:3072',
            'image5' => 'image|mimes:jpeg,png,jpg,gif,svg|max:3072',
        ];

$msg = [
            'image1.required' => 'Image is required',
            'image1.image' => 'Please upload an Image for Image ',
            'image1.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
            'image1.max' => 'Image size should be less than or equal 3MB',
            'image2.image' => 'Please upload an Image for Image ',
            'image2.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
            'image2.max' => 'Image size should be less than or equal 3MB',
            'image3.image' => 'Please upload an Image for Image ',
            'image3.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
            'image3.max' => 'Image size should be less than or equal 3MB',
            'image4.image' => 'Please upload an Image for Image ',
            'image4.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
            'image4.max' => 'Image size should be less than or equal 3MB',
            'image5.image' => 'Please upload an Image for Image ',
            'image5.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
            'image5.max' => 'Image size should be less than or equal 3MB',
        ];

$this->validate($req, $rules, $msg);

Please can you tell me if there is a better way to do this? :)


Solution

  • Use Array instead of giving name to file

    Laravel Validation rule for Multiple file.

    $rule = ['image.*' => 'required|mimes:jpeg,png,jpg,gif,svg|max:3072'];
    $msg = ['image.*.image' => 'Please upload an Image for Image ',
            'image.*.mimes' => 'Image type should be jpeg or jpg or png or gif or svg',
            'image.*.max' => 'Image size should be less than or equal 3MB'];