How to do validation for multiple images upload in laravel 5.3
Asked Answered
D

2

17

I've an input

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

and controller function

public function upload(Request $request)
{
    $user_id = Auth::user()->id;

    foreach ($request->image as $image)
    {
        $this->validate($request,[
        'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    ]);
        $imageName = mt_rand() .time().'.'.$image->getClientOriginalExtension();
        $img = Image::make($image->getRealPath());
        $img->resize(100, 100, function ($constraint) {
                                    $constraint->aspectRatio();
                    })->save(public_path('images/thumbs').'/'.$imageName);
        $image->move(public_path('images'), $imageName);
    }
}

but all the time validator gives me error that

    The image must be an image.
Disgusting answered 27/9, 2016 at 14:33 Comment(0)
C
49

Move validation outside the loop and try with the rules:

 'image' => 'required',
 'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
Crosson answered 27/9, 2016 at 15:8 Comment(4)
this is best answerCrofton
It worked, but can you explain a bit deeply, why it should be outside?Chrysolite
The first directive, "image", is for the field. The second directive, "image.*", is for the files themselves. In your loop, you were essentially validating the field over and over.Aeroballistics
@Aeroballistics that was an explanation I would like to have found in all the other threads out there. Thanks for pointing that out, about the 'image' and 'image.*'Coheir
J
0
foreach ($images as $img) {
    $request->validate([
       'multi_img.*' => ['required', 'image', 'mimes:jpeg,png,jpg', 'max:2048'],
     ]);}
Jepum answered 13/12, 2022 at 16:17 Comment(1)
Welcome to SO! Please don't post code-only answers but add a little textual explanation about how and why your approach works and what makes it different from the other answers given. You can find out more at our "How to write a good answer" page.Adair

© 2022 - 2024 — McMap. All rights reserved.