smallt's avatar

How to upload multi files images in Laravel

I want to upload multiple files and save their path into one column using comma separator, i am trying it but not get 100% result.

Right now images or files are uploaded into path but it save only first file name in db.

Here is my code

    public function postEditTourInfo(Request $req)
    {
        $tourDetail = TourDetail::findOrFail($req->id);
        if ($req->file('tour_info_image')) {
            foreach ($req->file('tour_info_image') as $media) {
                if (!empty($media)) {
                    $destinationPath = 'source\img\tour';
                    $filename = $media->getClientOriginalName();
                    $media->move($destinationPath, $filename);
                }
            }
        }
        $tourDetail->tour_image_detail = $tourDetail->tour_image_detail.','.$filename;
        $tourDetail->save();

        echo json_encode(TourDetail::find($req->id));
    }

My form

 <div class="form-group col-md-12">
              <h3 style="margin-bottom: 10px;">Images for slide</h3>
              <input type="file" class "form-control" multiple="multiple" name="hotel_info_image[]" id="hotel_info_image">
            </div> 
0 likes
6 replies
Sauravkc's avatar

That's because you are saving multiple files in for-each loop which is correct but saving to database only once.

foreach ($req->file('tour_info_image') as $media) {
                if (!empty($media)) {
                    $destinationPath = 'source\img\tour';
                    $filename = $media->getClientOriginalName();
                    $media->move($destinationPath, $filename);
            $tourDetail->tour_image_detail = $tourDetail->tour_image_detail.','.$filename;
                $tourDetail->save();
                }
            }
smallt's avatar

Thanks your very much. Now working but only a small issue is that it start with , it

 <pre>string(42) ",slide3.jpg,slide4.jpg,slide-thailand1.jpg" 
Snapey's avatar

create an array of file names then implode them at the end.

$files=[];

foreach ($req->file('tour_info_image') as $media) {
    if (!empty($media)) {
        $destinationPath = 'source\img\tour';
        $filename = $media->getClientOriginalName();
        $media->move($destinationPath, $filename);

        $files[] = $filename;
    }
}
$tour_detail->tour_image_detail = implode(',',$files);
$tourDetail->save();   

(really should not be answering this as creating comma separated fields is just a clear code smell for bad design)

kinnari's avatar

where is in video of multiple image upload this site? I didn't find..please tell me I want to again subscribe.please help me

Please or to participate in this conversation.