henryoladj's avatar

Laravel Image Upload Not Working

I am trying to upload multiple images into my database but instead it is only one image that is saving into the database, how can i correct this

if ($request->hasfile('image'))
          {
            foreach($request->file('image') as $image)
            {
                $filename = time().'.'.$image->extension();
                $location = public_path('image/'.$filename);
                Image::make($image)->resize(800, 400)->save($location);
                $data[] = $filename;
            }
            
            
         }
        
        //store

            $news->image = $filename;
            $image->image =json_encode($data);
            $news->save();

        return redirect()->route('news.index');
    }

View

<div class="form-group">
  <label for="image"><b>Select Image To Add</b></label>
  <input type="file" name="image[]" multiple>
</div>
0 likes
1 reply
bobbybouwmann's avatar

The part of parsing the multiple images works fine! However, you're overriding the $filename variable in the look an, therefore, it only saves one image. Try this instead

if ($request->hasfile('image')) {
    foreach($request->file('image') as $image) {
        $filename = time().'.'.$image->extension();
        $location = public_path('image/'.$filename);

        Image::make($image)->resize(800, 400)->save($location);

        // Save the image here instead of later

        $news->image = $filename;
        $news->save();
    }
}

return redirect()->route('news.index');

Note that this won't work as well, because you upload multiple images. Your model only accepts one image. So instead you need a one-to-many relationship here to connect each image.

Documentation: https://laravel.com/docs/6.x/eloquent-relationships#one-to-many

The relationship is not required, but in general, a better approach than the tutorial you've been following: https://appdividend.com/2018/02/05/laravel-multiple-images-upload-tutorial/ This should work as the tutorial suggested.

Please or to participate in this conversation.