0

I am new to laravel. I am trying to upload multiple files, but when I try to upload the same filenames at the same time, it crashes. how to prevent uploading same image names.

What I have tried is:

Html code:

<form method="POST" action="/listingSave" enctype="multipart/form-data" class="sellingFormSave" id="sellingFormSave" onsubmit="validate();">
    <div class="row">
        <div class="col-12 section_title-js">
            <h3></h3>
        </div>
        <div class="form-group col-md-12">
            <input id="demo" type="file" name="files" accept=".jpg, .png, image/jpeg, image/png" multiple>

        </div>
    </div>
    <button type="submit" class="btn" id="submit">
            Save
    </button>
</form>

Controller.php

public function listingSave(Request $request) {
   if(array_key_exists('image', $request->all())){
        
      $imageName = $request->imageName;
     
      $image = $request->image;
        foreach ($image as $key => $value) {         
          $image_name = date('mdYhis').'_'.$imageName[$key]; 
           
          $imgdata = base64_decode($value);
          $myOutput = public_path().'/app/default/files-module/local/images/'.$image_name;
          $ifp = fopen( $myOutput, 'wb' ); 
          fwrite( $ifp, $imgdata );
          fclose( $ifp );    
          $imageInfo = getimagesize($myOutput);
          $files = FileModel::updateOrCreate(['name'=>$image_name],[
              // 'sort_order'=>$truckian->id+$key,
              'sort_order'=>0+$key,
              'created_at'=>date('Y-m-d H:i:s'),
              'updated_at'=>date('Y-m-d H:i:s'),
              // 'created_by_id'=>Auth::user()->id,
              'created_by_id'=>0,
              'disk_id'=>1,
              'folder_id'=>1,
              'extension'=>str_replace('image/', '', $imageInfo['mime']),
              'size'=>$imageInfo[0]*$imageInfo[1],
              'mime_type'=>$imageInfo['mime'],
              "entry_type" => "Anomaly\Streams\Platform\Model\Files\FilesImagesEntryModel",
              "height" => $imageInfo[1],
              "width" => $imageInfo[0],
            ]);
          // DB::table('truckian_products_image')->insert(['entry_id'=>$truckian->id,'file_id'=>$files->id,'sort_order'=>$key+1]);
          DB::table('truckian_products_image')->insert(['entry_id'=>$p_id,'file_id'=>$files->id,'sort_order'=>$key+1]);
        }
        foreach($available as $key => $value)
        DB::insert('insert into default_truckian_mileage_gap(mileage_gap,number_of_products,truck_id)values (?,  ?, ?)',[$key,$value,$p_id]);
    }


}

Whenever I execute same file names, it crashes. How to fix this.

5
  • Are you getting any errors? Commented Nov 21, 2021 at 23:21
  • @Dula Yes I am getting like this . SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '40-8897' for key 'c72333b5ba020bf52db5233c89a40c13' (SQL: insert into default_truckian_products_image (entry_id, file_id, sort_order) values (40, 8897, 2)) Commented Nov 21, 2021 at 23:30
  • I think the error is generated from the place where you are trying to insert data to default_truckian_products_image table. Commented Nov 22, 2021 at 0:31
  • @Dula No, it has no error, when unique names are uploading, but when I try to upload same images , this error occur. Commented Nov 22, 2021 at 2:47
  • there may be constrain added for id and file name in you DB. You should remove it from table schema OR try to append some random name to file name Commented Nov 22, 2021 at 10:16

1 Answer 1

0

Try to use incrementor variable like below in defining file name in foreach loop

$i = 0;
foreach ($image as $key => $value) {         
      $image_name = date('mdYhis').'_'.$i.'_'.$imageName[$key];
      //other code
      $i++;
}

It will create different names for file everytime even if its uploaded at same time

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.