File upload using foreach in Laravel

I see that you are trying to store the files directly in public folder, but why not use the Storage API of Laravel and use the public disk? You can do something like this to upload the files to the public directory:

$id = 123;
$files = $request->file();
$folder = $id;
if (count($files) > 0) {
    foreach ($files as $file) {
        $file->store($folder, ['disk' => 'public']);
    }
}

And be sure that you have linked the storage path to public:

php artisan storage:link

Focus on $files = $request->file(); line. When you don't pass an argument to file() method, all uploaded file instances are returned. Now when you will loop over the $files array, you will get access to individual uploaded files.

And then you can store the file using your logic, i.e. you can use the original name or whatever else. Even you can use the Storage facade to process the file instance.

i.e. if you want to store the files with their original names, I find this a cleaner way rather than what you are doing:

$id = 123;
$files = $request->file();
$folder = $id;
if (count($files) > 0) {
    foreach ($files as $file) {
        Storage::disk('public')->putFileAs(
            $folder,
            $file,
            $file->getClientOriginalName()
        );
    }
}

And as suggested by @cbaconnier, you can use allFiles() method too that's more descriptive:

$files = $request->allFiles();

I hope this helps.

Tags:

Laravel