1

I'm trying to save images from the form input. But it's not working. I have code as following: View:

<form role="form" method="post" action="store" enctype="multipart/form-data">
<label class="control-label">Select Images</label>
<input id="image" name="image[]" multiple type="file">

Controller:

public function store(Request $request)
    {

          $image = $request->file('image');

        $input['imagename'] = time().'.'.$image->getClientOriginalExtension();

        $destinationPath = public_path('/images');

        $image->move($destinationPath, $input['imagename']);


        $this->postImage->add($input);

}

The $image in controller is returning nothing when i tried return($image). What is wrong in here? Can anyone help me?

2 Answers 2

1

You have array of images in <input id="image" name="image[]" multiple type="file">. So you need to run foreach to get images from that array. If you want to upload single image please remove [] from image and write input like this:

<input id="image" name="image" type="file">
Sign up to request clarification or add additional context in comments.

4 Comments

It worked for the single file. But when i tried to use foreach at the controller like: foreach ($image as $image) { $image = $request->file('image'); $input['imagename'] = time().'.'.$image->getClientOriginalExtension(); $destinationPath = public_path('/images'); $image->move($destinationPath, $input['imagename']); } It is showing an error of undefined variable:image. What's wrong in here?
At first if you want to upload multiple files leave your input file as array and add attribute multiple as was in your post up there. Than you have to write foreach like this: foreach ($request->file('image') as $i) { $image = $i; $input['imagename'] = time().'.'.$image->getClientOriginalExtension(); $destinationPath = public_path('/images'); $image->move($destinationPath, $input['imagename']); }
It is only saving 1 image.
It may be the problem of time. Time can get the same value if is called during one second. please instead of time() use str_random(32);
0

can you change below code to

$image = $request->image('file');

and try.

1 Comment

Please explain the difference, how it works, how you predict it to change the behaviour and why you think it will solve the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.