15

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.

2 Answers 2

46

Move validation outside the loop and try with the rules:

 'image' => 'required',
 'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
4
  • 1
    this is best answer Nov 13, 2017 at 17:59
  • It worked, but can you explain a bit deeply, why it should be outside? Jun 20, 2018 at 11:57
  • 4
    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. Aug 5, 2018 at 12:55
  • @misdreavus79 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.*' Nov 18, 2019 at 19:20
0
foreach ($images as $img) {
    $request->validate([
       'multi_img.*' => ['required', 'image', 'mimes:jpeg,png,jpg', 'max:2048'],
     ]);}
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.
    – ahuemmer
    Dec 16, 2022 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.