1

I wrote these code for upload files through laravel 6.

But I only success for upload one file,even I am sure I got all files while uploading by check from dd($request->files)

in the begining the $index = 0 and in the end it change to 1,first round is ok but the it didn't continue to second run.

I don't know why,please help! thank you~

if($request->hasFile('files')){
    
    $index = 0;
    foreach($request->files as $key=>$file){

        $originalName = $file[$index]->getClientOriginalName();
        $size = $file[$index]->getClientSize();
        $ext = $file[$index]->getClientOriginalExtension();
        $newName = date('Ymd').mt_rand(100,999).$originalName;

        $savePath = '/attachments/'.$newName;
        $movePath = base_path().'/public/attachments/'.$newName;
 
        $file[$index]->move(base_path().'/public/attachments',$newName);

        $attachment = new attachment();
        $attachment->bulletin_id = $bulletin->id;  //already got this value before
        $attachment->original_name = $originalName;
        $attachment->name = $newName;
        $attachment->type = $file[$index]->getClientMimeType();
        $attachment->path = $savePath;
        $attachment->size = ($size/1000);
        $attachment->save();
        ++$index;
    }
}
1
  • Don't use index instead of use foreach key for the save functionality Commented Aug 16, 2021 at 4:14

1 Answer 1

1

You try this way and it is simple

foreach($request->file('files') as $key=>$file){

$originalName = $file->getClientOriginalName();
$size = $file->getClientSize();
$ext = $file->getClientOriginalExtension();
$newName = date('Ymd').mt_rand(100,999).$originalName;

$savePath = '/attachments/'.$newName;
$movePath = base_path().'/public/attachments/'.$newName;

$file->move(base_path().'/public/attachments',$newName);

$attachment = new attachment();
$attachment->bulletin_id = $bulletin->id;  //already got this value before
$attachment->original_name = $originalName;
$attachment->name = $newName;
$attachment->type = $file->getClientMimeType();
$attachment->path = $savePath;
$attachment->size = ($size/1000);
$attachment->save();

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

1 Comment

No problem ! Your kind make people life better. : )

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.