Save multiple images in a php loop

Asked

Viewed 195 times

1

People I have the code below in Laravel that saves a single image and works correctly. But I would like to save multiple images that come from an input that is named:"name[]" Multiple. I think I would need a go but I couldn’t make it work.

public function store(Request $request)
{
    $input = $request->all();
    $modality = new Modality($input);
    $modality->save();

    $image = $request->image; //Array de imagens

    $imageName = $image->getClientOriginalName();
    $image = new Image();
    $image->name = $imageName;
    $image->imageable_id = $modality->id;
    $image->imageable_type = Modality::class;
    $path = $request->file('image')->storeAs('public', $imageName);
    $image->save();
    return redirect()->action('ModalityController@index');
}

1 answer

3


The initial logic is using foreach to scan all items from the image list as shown below:

public function store(Request $request)
{
    $input = $request->all();
    $modality = new Modality($input);
    $modality->save();

    //Declarado com o nome da variável $images  
    $images = $request->image; //Array de imagens

    ///////// FOREACH da lista de imagens.
    foreach($images as $im)
    {
        $image = new Image();
        $image->name = $im->getClientOriginalName();
        $image->imageable_id = $modality->id;
        $image->imageable_type = Modality::class;
        $path = $im->storeAs('public', $im->getClientOriginalName());
        $image->save();    
    }
    return redirect()->action('ModalityController@index');

}
  • In your code is giving error in $file.

  • I changed it to: $path = $value->storeAs('public', $value->getClientOriginalName()); and it worked.

  • @Marcelo is $im actually it was a typo.!

  • 1

    Right. It worked, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.