Skip to content
Advertisement

Files are repeated when uploading pictures to Laravel

I want to do bulk image upload on my blog that I write in Laravel. Wrote the code for loading images. Everything works, but the images are repeated

$images = [];
$urls = [];

if ($request->hasFile('images')) {
    foreach($request->file('images') as $key => $image){
        $images[] = Storage::putFile('public/' . Auth::user()->id . '/post', $image);
        foreach($images as $img) {
            $urls[] = Storage::url($img);
        }
    }
    $post->post_images = serialize($urls);
}

After loading 6 images, I get this array of 21 elements. What’s wrong?

Advertisement

Answer

You’re appending $images to $urls on each image. Do it like this instead, appending images to $urls after all images are processed:

$images = [];
$urls = [];

if ($request->hasFile('images')) {
    foreach($request->file('images') as $key => $image){
        $images[] = Storage::putFile('public/' . Auth::user()->id . '/post', $image);
    }
    foreach($images as $img) {
        $urls[] = Storage::url($img);
    }
    $post->post_images = serialize($urls);
}

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement