Laravel-medialibrary: How to handle multiple file inputs with addMediaFromRequest?

Created on 12 May 2016  Â·  4Comments  Â·  Source: spatie/laravel-medialibrary

So the addMediaFromRequest expects the request key
in my case the request key is images[] so it is an array of files
after which the key becomes and integer.

multiple-file-upload

so $request->file('images') returns this:

array:2 [â–¼
    0 => UploadedFile {#364 â–¶}
    1 => UploadedFile {#356 â–¶}
  ]

when i do this

$report->addMediaFromRequest('images')->toCollection('medical-reports');

i get this error

FileCannotBeAdded in FileCannotBeAdded.php line 13:
Only strings, FileObjects and UploadedFileObjects can be imported

and when I do this

foreach($request->file('images') as $image){
            $report->addMediaFromRequest($image)->toCollection('medical-reports');
        }

I get this error

FileCannotBeAdded in FileCannotBeAdded.php line 49:
The current request does not have a file in a key named `C:\wamp64\tmp\php3894.tmp`

Which is the true, the request does not have any key names by the tmp upload path of the file

Now I am not sure how to feed the addMediaFromRequest method...

Most helpful comment

When uploading multiple files with the same name in the request, do not use addMediaFromRequest

Get the files of the request and add them manually.

Try this:

foreach($request->file('images') as $image) {
   $report->addMedia($image)->toCollection('medical-reports');
}

Reopen if you are still having problems.

All 4 comments

When uploading multiple files with the same name in the request, do not use addMediaFromRequest

Get the files of the request and add them manually.

Try this:

foreach($request->file('images') as $image) {
   $report->addMedia($image)->toCollection('medical-reports');
}

Reopen if you are still having problems.

I was looking for the same answer for Laravel Medialibrary v.7 here. The following code works for me.

foreach($request->file('images') as $image) {
   $report->addMedia($image)->toMediaCollection('medical-reports');
}

I only need to change toCollection() to toMediaCollection(). Thanks @kickthemooon and @freekmurze.

@freekmurze how can I show these media in list view page?

@freekmurze how can I show these media in list view page?

try to add it to specific media collection then use getMedia('collection_name') to get media

Was this page helpful?
0 / 5 - 0 ratings

Related issues

intrepidws picture intrepidws  Â·  3Comments

aaronfullerton picture aaronfullerton  Â·  4Comments

netanelwebninja picture netanelwebninja  Â·  3Comments

ideadx picture ideadx  Â·  4Comments

mohammad6006 picture mohammad6006  Â·  4Comments