pordonez's avatar

Laravel : add additional upload file from public folder

my system can upload files and keep it in the public folder, but what i need is i can upload more images from the same folder without removing the old images

here is my controller.

//Boiler Add More Files
    public function boiler_success_pibi(Request $request, $slug) {
        if($request->hasFile('pibi')) {

            $path = public_path().'/raw/boiler/'.$slug.'/pibi/';

            if(!File::exists($path)) {
                File::makeDirectory($path, $mode = 0777, true, true);
            }
            $count = 0;
            foreach($request->file('pibi') as $pibi) {
                $count++;
                $extension = $pibi->getClientOriginalExtension();
                $filename = 'PIBI-'.$slug.'-'.$count.'.'.$extension;
                $pibi->move($path, $filename);
                $data_pree[] = $filename;
            }
        } else {
            $data_pree = "";
        }
    }

with that codes, my uploaded files is only replacing the images that i uploaded before.

0 likes
6 replies
theUnforgiven's avatar

I'd personally use DropZoneJS to upload multiple files and use AmazonS3 or something for the storage.

But to get around your issue, what about changing

$filename = 'PIBI-'.$slug.'-'.$count.'.'.$extension; to something like $filename = 'PIBI-'.$slug.'-'.time().'.'.$extension; that way it would be unique and not remove old images.

pordonez's avatar

@theUnforgiven hi, yes im using DropZone, but it is only replacing files with the same name, is there anyway to not to do that?.

pordonez's avatar

if im trying to upload multiple images at once it will only keep only 1 image.

Yorki's avatar

So basically you have some naming convention like 'PIBI-'.$slug.'-'.$count.'.'.$extension, based on this you could scan directory and get last count as offset for your new files.

$path = public_path().'/raw/boiler/'.$slug.'/pibi/';

if (!File::exists($path)) {
    File::makeDirectory($path, $mode = 0777, true, true);
}

$files = File::files($path);
$count = 0;

if (!empty($files)) {
    $ids = [];

    foreach ($files as $file) {
        preg_match('/\-([0-9]+)\./', $file->getFilename(), $matches);

        if (isset($matches[1])) {
            $ids[] = $matches[1];
        }
    }

    $count = max($ids);
}

foreach ($request->file('pibi') as $pibi) {
    $count++;
    $extension = $pibi->getClientOriginalExtension();
    $filename = 'PIBI-'.$slug.'-'.$count.'.'.$extension;
    $pibi->move($path, $filename);
    $data_pree[] = $filename;
}

1 like
Yorki's avatar

@pordonez was this you were looking for? If so you can mark this as solved thread.

Please or to participate in this conversation.