samedi 10 avril 2021

Laravel 5 | File upload - If file exists add number to filename

I have problem with file upload. Now I have something like this (part of Controller):

if($request->has('photos')) {
            foreach ($request->photos as $photo) {
                $filename = $photo->getClientOriginalName();
                $tmp_name = $filename;

                if ($pos = strrpos($filename, '.')) {
                    $name = substr($filename, 0, $pos);
                    $ext = substr($filename, $pos);
                    
                } else {
                    $name = $filename;
                }

                $uniq_no = 0;
                while (file_exists($filename)) {
                    $tmp_name = $name .'_'. $uniq_no . $ext;
                    $uniq_no++;
                    
                }
                $photo->storeAs('public/photos/',$tmp_name);
                Photo::create([
                    'page_id' => $page->id,
                    'filename' => $tmp_name
                ]);
            }
        }

but saves to the database without adding a unique number: filename_0, filename_1 etc. It just saves the value of $tmp_name.

What am I doing wrong?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire