简体   繁体   中英

Only last image is uploading while trying to upload an array of images in Laravel 5.8

I'm trying to upload an array of objects to my laravel db, one of the properties of the objects in the array (backgroundImgRaw) has a file.

I have to loop through the array to upload all images and get the file name so as to save to db. But only the last file gets uploaded and the name is returned for all iteration.

DB::transaction(function () use ($request) {
...

foreach ($request->slides as $slides) {
   $backgroundImg = null;

   if (isset($slides['backgroundImgRaw'])) {
       $img_ext = $slides['backgroundImgRaw']->getClientOriginalExtension();
       $img_name = Str::slug($request->user['name'], '-') . '_img_' . time() . '.' . $img_ext;
       $slides['backgroundImgRaw']->storeAs('public/images/' . $request->user['email'], $img_name);
       $backgroundImg = env('CUSTOM_URL', false) . '/storage/images/' . $request->user['email'] . '/' . $img_name;
       Log::info(json_encode($backgroundImg->getoriginalfilename(), JSON_PRETTY_PRINT));
   } else {
       $backgroundImg = $slides['backgroundImg'];
   }
}

$slide = Slide::create([
   'slide_type' => isset($slides['subType']) ? $this->getSlidetype($slides['subType']) : null,
   'layout_type' => $slides['type'],
   'survey_id' => $request->surveyId,
   'background_color' => isset($slides['backgroundColor']) ? $slides['backgroundColor'] : null,
   'background_imageURL' =>  $backgroundImg,
   'screenshot' => $slidescreenshot,
   'text_color' => isset($slides['textColor']) ? $slides['textColor'] : null,
   'button_background' => isset($slides['buttonBackground']) ? $slides['buttonBackground'] : null,
   'button_text_color' => isset($slides['buttonTextColor']) ? $slides['buttonTextColor'] : null,
   'main_text' => $mainText,
   'button_text' => isset($slides['btnText']) ? $slides['btnText'] : null
]);

...
}

Only the last image is uploaded. But the rest of the create function works perfectly.

$request->slides returns an array in this format

[
    {
        "id": "1",
        "type": "2",
        "backgroundColor": "#203661",
        "backgroundImg": "blob:http:\/\/localhost:3000\/4089c09c-caeb-4121-a2a3-9d7aaf20264d",
        "backgroundImgRaw": {},
    ...
    },
    {
        "id": "3",
        "type": "1",
        "backgroundImg": "blob:http:\/\/localhost:3000\/bc13e931-cb0a-425a-b3c6-2db6dbbdd5a4",
        "backgroundImgRaw": {},
    ...
    }
]

For anyone having a similar issue the problem is with the $img_name variable, time() goes down to the second so all the images were processed within the same second, so new images just keep overwriting previous images. I have updated the line to:

$img_name = Str::slug($request->user['name'], '-') . '_img_' . str_random(10) . '.' . $img_ext;

Only last image is saving because you put the create outside the foreach loop. You must put it inside the loop.

I also noticed that you are using time() to generate random image name. This is not the ideal way to do it because your code is executing so fast that all of the slide is generating the same time() . You can use Laravel's Str::random function.

Here are my suggested code:

use Illuminate\Support\Str;
...
DB::transaction(function () use ($request) {
...

foreach ($request->slides as $slides) {
   $backgroundImg = null;

   if (isset($slides['backgroundImgRaw'])) {
       $img_ext = $slides['backgroundImgRaw']->getClientOriginalExtension();
       $img_name = Str::slug($request->user['name'], '-') . '_img_' . Str::random(6) . '.' . $img_ext;
       $slides['backgroundImgRaw']->storeAs('public/images/' . $request->user['email'], $img_name);
       $backgroundImg = env('CUSTOM_URL', false) . '/storage/images/' . $request->user['email'] . '/' . $img_name;
       Log::info(json_encode($backgroundImg->getoriginalfilename(), JSON_PRETTY_PRINT));
   } else {
       $backgroundImg = $slides['backgroundImg'];
   }

   $slide = Slide::create([
      'slide_type' => isset($slides['subType']) ? $this->getSlidetype($slides['subType']) : null,
      'layout_type' => $slides['type'],
      'survey_id' => $request->surveyId,
      'background_color' => isset($slides['backgroundColor']) ? $slides['backgroundColor'] : null,
      'background_imageURL' =>  $backgroundImg,
      'screenshot' => $slidescreenshot,
      'text_color' => isset($slides['textColor']) ? $slides['textColor'] : null,
      'button_background' => isset($slides['buttonBackground']) ? $slides['buttonBackground'] : null,
      'button_text_color' => isset($slides['buttonTextColor']) ? $slides['buttonTextColor'] : null,
      'main_text' => $mainText,
      'button_text' => isset($slides['btnText']) ? $slides['btnText'] : null
   ]);
}

...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM