laravel 10 multiple image uploading not working gives me a error
the code works fine when i modify the code to do it with one picture
<form action="/addbg" method="post" enctype="multipart/form-data">
@csrf
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<label for="formFileMultiple" class="form-label">Add Background Images</label>
<input class="form-control" type="file" name="imageid[]" multiple>
<br>*Select at least 3 images
<br><br>
<p><input type="submit" class="btn btn-primary" role="button"></input></p>
</form>
class siteconfigcontroller extends Controller
{
public function store(Request $request): RedirectResponse
{
//foreach (($request->file('imageid')) as $imageid){}
foreach($request->file("imageid[]") as $key => $image){
//$image = $request->file('imageid[]');
$namegen=hexdec(uniqid());
$imgextension=strtolower($image->getClientOriginalExtension());
$imgname=$namegen.'.'.$imgextension;
$up_location='image/bg/';
$lastimg=$up_location.$imgname;
$image->move($up_location,$imgname);
}
return redirect('siteconfig');
}
}
Can someone figure this out for me
2
Answers
Tested 100% working
When you send array of inputs with HTML. You should not use the
[]
in name of input!You can simply loop through it using a
for
and grab every file out of it.But there is a note about array files in laravel you cannot use
foreach
to loop through them! Just use afor
loop as I did:In your HTML form, add the multiple attribute to the file input field:
<input type="file" name="imageid[]" multiple>
In your controller, use the store() method of the UploadedFile class to save each file:
This code assumes that you have a public/uploads directory in your Laravel project where the files will be stored. If you want to store the files in a different directory, you can change the argument of the store() method accordingly.