0

I've stuck many days when I am trying to upload image files. I can't upload multiple images files with code below:

Controller

if ($request->TotalImages > 0) {

            for ($x = 0; $x < $request->TotalImages; $x++) {

                if ($request->hasFile('images' . $x)) {
                    $file      = $request->file('images' . $x);

                    $path = $file->store('public/product_images/');
                    $name = $file->getClientOriginalName();

                    $insert[$x]['name'] = $name;
                    $insert[$x]['path'] = $path;
                }
            }
        }

        $productId = DB::table('products')->insertGetId(
            [
                'product_photo' => $insert
            ]
        );

View

<input id="images" name="images[]" type="file" multiple
                            class="form-control {{ $errors->first('images') ? 'is-invalid' : '' }}"
                            data-iconName="fa fa-upload" data-overwrite-initial="false">
                        <br>
var formData = new FormData();
let TotalImages = $('#images')[0].files.length; //Total Images
        let images = $('#images')[0];
        for (let i = 0; i < TotalImages; i++) {
            formData.append('images' + i, images.files[i]);
        }
        formData.append('TotalImages', TotalImages);

        $.ajax({
            url: "{{ route('products.store') }}",
            method: 'post',
            enctype: 'multipart/form-data',
            cache: false,
            data: formData,
            contentType: false,
            processData: false,
            dataType: 'JSON',
            async: true,
            headers: {
                'Content-Type': undefined,
            },
            xhr: function() {
                myXhr = $.ajaxSettings.xhr();
                return myXhr;
            },
            
        }); //ajax

It always show me an error:

The images field is required.

But with single upload it works!

1 Answer 1

1

You should encoding a variable before you insert to database. And dont validate an image in the very beginning. Validating an image only comes after you've checked if ($request->TotalImages > 0), if TotalImages === 0 then validate an image.

if ($request->TotalImages > 0) {

        for ($x = 0; $x < $request->TotalImages; $x++) {

            if ($request->hasFile('images' . $x)) {
                $file      = $request->file('images' . $x);

                $path = $file->store('public/product_images/');
                $name = $file->getClientOriginalName();

                $insert[$x]['name'] = $name;
                $insert[$x]['path'] = $path;
            }
        }

$productId = DB::table('products')->insertGetId(
        [
            'product_photo' => json_encode($insert)
        ]
    );

    } else { $imageValidator = \Validator::make($request->all(), [
                'images' => 'required|file|mimes:jpeg,png,jpg,gif,svg',
            ]);
            return response()->json(['errors' => $imageValidator->errors()->all()]);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.