Ariando
Ariando

Reputation: 1421

How to validate multiple images input?

I have this function which will allow users to upload one image or more. I already create the validation rules but it keep returning false no matter what the input is.

Rules :

public function rules()
    {
        return [
            'image' => 'required|mimes:jpg,jpeg,png,gif,bmp',
        ];
    }

Upload method :

public function addIM(PhotosReq $request) {
        $id = $request->id;
        // Upload Image
        foreach ($request->file('image') as $file) {
            $ext = $file->getClientOriginalExtension();
            $image_name = str_random(8) . ".$ext";
            $upload_path = 'image';
            $file->move($upload_path, $image_name);
            Photos::create([
                'post_id' => $id,
                'image' => $image_name,
            ]);
        }
        //Toastr notifiacation
        $notification = array(
            'message' => 'Images added successfully!',
            'alert-type' => 'success'
        );
        return back()->with($notification);
    }

How to solve this ? That's all and thanks!

Upvotes: 0

Views: 2658

Answers (1)

Sagar Gautam
Sagar Gautam

Reputation: 9369

You have multiple image upload field name like and add multiple attribute to your input element

<input type="file" name="image[]" multiple="multiple">

So that, your input is like array inside which there will be images. Since there is different method for array input validation, see docs here.

So, you have to validate something like this:

$this->validate($request,[
     'image' => 'required',
     'image.*' => 'mimes:jpg,jpeg,png,gif,bmp',
]);

Hope,You understand

Upvotes: 4

Related Questions