Flex

Why did not save multiple images with controller route return?

Posted 2 months ago by Flex

In my Laravel app I have form to save multiple images to save uploads table, my form as following,

<form method="post" action="{{url('form')}}" enctype="multipart/form-data"> 
            {{csrf_field()}}
<div class="form-group row required">
            <div class="field" align="left" >
            <h3>Upload  images</h3>
            <input type="file" class="files" name="files[]" multiple />
            <input type="file" class="files" name="files[]" multiple />
            <input type="file" class="files" name="files[]" multiple />
            <input type="file" class="files" name="files[]" multiple />
            </div>
</div>

and controller store function is,

$photos = $request->file('files');

        if (!is_array($photos)) {
            $photos = [$photos];
        }

        if (!is_dir($this->photos_path)) {
            mkdir($this->photos_path, 0777);
        }

        for ($i = 0; $i < count($photos); $i++) {
            $photo = $photos[$i];
            $name = sha1(date('YmdHis') . str_random(30));
            $save_name = $name . '.' . $photo->getClientOriginalExtension();
            $resize_name = $name . str_random(2) . '.' . $photo->getClientOriginalExtension();

            Image::make($photo)
                ->resize(250, null, function ($constraints) {
                    $constraints->aspectRatio();
                })
                ->save($this->photos_path . '/' . $resize_name);

            $photo->move($this->photos_path, $save_name);

            $upload = new Upload();
            $upload->filename = $save_name;
            $upload->resized_name = $resize_name;
            $upload->original_name = basename($photo->getClientOriginalName());
            
            $upload->save();
return redirect()->route('categories.categorypost')->with('info','Your Advertisment has been created successfully');

but when I attach 4 images in above form. it is saving only one image. that attach to first input file. why other images are not saving to table. but when i remove return following codes

return redirect()->route('categories.categorypost')->with('info','Your Advertisment has been created successfully');

then I can save all images. but I need above controller return and saving all images. how can I do this?

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.