Save multiple images in a php loop

1

Personal 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 looks like name: "name []" multiple. I think I would need a for but I could not get it to 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');
}
    
asked by anonymous 01.05.2017 / 17:18

1 answer

3

The initial logic is to use foreach to scan all items in 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');

}
    
01.05.2017 / 17:35