Lazarus
Lazarus

Reputation: 11

Laravel 6 - How to upload multi file through laravel?

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;
    }
}

Upvotes: 1

Views: 62

Answers (1)

A.A Noman
A.A Noman

Reputation: 5270

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();

}

Upvotes: 1

Related Questions