John Davidson

php - Uploading multiple files with laravel

0 comments
Message:


I am currently trying to upload multiple files through an API endpoint. It's a POST request, its body contains form-data.


I am unable to get it through for each loop, though it works just fine if there's no foreach and there's only one file.


Code that doesn't work:


$path = config('app.photos_dir');

if($request->hasFile('photos'))
{
if (!file_exists($path)) {
mkdir($path, 0777, true);
}
try {
$files = $request->file('photos');

foreach ($files as $file){
$file->move($path, $files->getClientOriginalName());
}

} catch (\Exception $exception) {

return response(['status' => '500', 'error' => 'Error while uploading files'], 500);
}

return response(['status' => '200', 'data' => ['Photos uploaded correctly']], 200);


}


As outlined above, it starts working once I remove foreach clause(although this will only upload the first/last file selected in the 'upload' windows prompt)


$files = $request->file('photos');
$files->move($path, $files->getClientOriginalName());

Not really sure what is wrong here. I found other folks which had no problems in looping through the request files, but in my case, it won't go no matter what I do.



My Answer:
>hasFile('photos')) {
foreach($request->file('photos') as $photo) {
$filename = $photo->getClientOriginalName();
$photo->move($path, $filename);
}
}

return response()->json(['message' => 'Files uploaded successfully']);
}

In this code snippet, we are trying to upload multiple files by iterating over the files in the request using a foreach loop. However, this code may not work as expected because the `file()` method returns an array of UploadedFile objects, and we need to use the `hasFile()` method to check if files are present in the request.

To fix this issue, we need to modify the code as follows:

php
$path = config('app.photos_dir');

if($request->hasFile('photos')) {
$photos = $request->file('photos');

foreach($photos as $photo) {
$filename = $photo->getClientOriginalName();
$photo->move($path, $filename);
}
}

return response()->json(['message' => 'Files uploaded successfully']);


By storing the files in a variable before iterating over them, we ensure that we are working with an array of UploadedFile objects. This should allow us to successfully upload multiple files using Laravel.

Rate this post

4 of 5 based on 9334 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us